Personal learning series – spring boot using cache

Time:2021-2-27

Back end development always needs to ensure that the faster the data returns, the better. However, database query is just that fast. Optimizing SQL and database configuration are not the most reasonable methods. So today we look at caching.

Cache

When it comes to caching, we always think of redis for the first time, but the most important thing is that redis needs to start the client itself, which is troublesome. We just need to cache simple data. What do we do? Springboot thought of this problem for us, so the cache concurrent mapcache manager is added by default.

1. Create a new springboot project

No more details, just refer to the previous article

2. Modification pom.xml file

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Here we use JPA.

3. Create a new database table

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(64) CHARACTER SET utf8 COLLATE utf8_ Bin null default null comment 'name',
  `address` varchar(512) CHARACTER SET utf8 COLLATE utf8_ Bin null default null comment 'address',
  `Age ` int null default null comment 'age',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

4. Write the code

4.1 creating a new entity class

/**
 *Entity class
 * @author zhouzhaodong
 */
@Entity
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private int id;

    private String name;

    private String address;

    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", age=" + age +
                '}';
    }
}

4.2 new database access layer inherits jparepository

/**
 *Database access layer
 * @author zhouzhaodong
 */
public interface UserRepository extends JpaRepository<User, Integer> {

    /**
     *Update by ID
     *
     * @param id
     * @param name
     * @param address
     * @param age
     */
    @Modifying
    @Query(value = "update user u set u.name = :name, u.address = :address, u.age = :age  where u.id = :id", nativeQuery = true)
    User updateById(@Param("id") Integer id,
                    @Param("name") String name,
                    @Param("address") String address,
                    @Param("age") int age);
}

4.3 define business layer classes

/**
 * Service
 * @author zhouzhaodong
 */
@Service
public interface UserService {

    /**
     *New
     * @param user
     * @return
     */
    User insert(User user);

    /**
     *Delete
     * @param id
     * @return
     */
    void delete(int id);

    /**
     *Update
     * @param user
     * @return
     */
    void update(User user);

    /**
     *Query by ID
     * @param id
     * @return
     */
    Object findById(int id);

}
/**
 *Implementation class
 * @author zhouzhaodong
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserRepository userRepository;

    @Override
    @CachePut(value = "user", key = "#result.id")
    public User insert(User user) {
        return userRepository.save(user);
    }

    @Override
    @CacheEvict(value = "user", key = "#id")
    public void delete(int id) {
        userRepository.deleteById(id);
    }

    @Override
    @CachePut(value = "user", key = "#user.id")
    public User update(User user) {
        return userRepository.updateById(user.getId(), user.getName(), user.getAddress(), user.getAge());
    }

    @Override
    @Cacheable(value = "user", key = "#id")
    public Object findById(int id) {
        return userRepository.findById(id);
    }
}

4.4 control layer

/**
 *Control layer
 * @author zhouzhaodong
 */
@RestController
public class UserController {

    @Resource
    UserService userService;

    @RequestMapping("/save")
    public User saveUser(User user){
        return userService.insert(user);
    }

    @RequestMapping("/delete")
    public void deleteUser(int id){
        userService.delete(id);
    }

    @RequestMapping("/update")
    public User updateUser(User user){
        return userService.update(user);
    }

    @RequestMapping("/find")
    public Object findById(int id){
        return userService.findById(id);
    }

}

4.5 add notes to startup class

/**
 *Startup class
 * @author zhouzhaodong
 */
@SpringBootApplication
@EnableCaching
public class CacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }

}

4.6 application configuration file

server:
  Port: 8989
spring:
  datasource:
    url:  jdbc:mysql : // IP address: 3306 / test? Characterencoding = utf8 & usessl = false & servertimezone = GMT% 2B8 & rewrite batched statements = true
    User name: user name
    Password: password
  jpa:
    Show SQL: true print SQL
    properties:
      hibernate:
        format_ SQL: true # print SQL

5. Post test

First, add new data, and then query, you will find that the database query does not go, the console does not print SQL, and the cache is successful.

Please refer to:

https://github.com/zhouzhaodo…

Personal blog:

http://www.zhouzhaodong.xyz/