转载

springboot缓存

后端开发总是要保证数据返回的速度越快越好,可是数据库查询就是那么个速度,通过优化SQL和数据库配置都不是最合理的方法。所以今天我们来看一下缓存。

Cache

话说缓存,我们总是第一时间想到redis,可是最关键的是redis需要自己启动客户端,这就比较麻烦了。我们只是需要缓存简单的数据怎么办?springboot为我们想到了这个问题,于是默认添加了缓存ConcurrentMapCacheManager。

1. 新建SpringBoot项目

不再赘述,参考之前的文章即可

2. 修改pom.xml文件

<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>

这里我们使用jpa。

3. 新建数据库表

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 '姓名',
  `address` varchar(512) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '地址',
  `age` int NULL DEFAULT NULL COMMENT '年龄',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

4. 写代码啦

4.1 新建实体类User

/**
 * 实体类
 * @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 新建数据库访问层继承JpaRepository

/**
 * 数据库访问层
 * @author zhouzhaodong
 */
public interface UserRepository extends JpaRepository<User, Integer> {

    /**
     * 根据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 定义业务层类

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

    /**
     * 新增
     * @param user
     * @return
     */
    User insert(User user);

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

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

    /**
     * 根据id查询
     * @param id
     * @return
     */
    Object findById(int id);

}
/**
 * 实现类
 * @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 控制层

/**
 * 控制层
 * @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 启动类添加注解

/**
 * 启动类
 * @author zhouzhaodong
 */
@SpringBootApplication
@EnableCaching
public class CacheApplication {

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

}

4.6 application配置文件

server:
  port: 8989 # 端口号
spring:
  datasource:
    url: jdbc:mysql://ip地址:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2b8&rewriteBatchedStatements=true
    username: 用户名
    password: 密码
  jpa:
    show-sql: true # 打印sql
    properties:
      hibernate:
        format_sql: true # 打印sql

5. post测试

首先新增数据,然后进行查询就会发现并不走数据库查询,控制台不打印sql,缓存成功。

详细代码请查看:

https://github.com/zhouzhaodong/springboot/tree/master/cache

原文  http://www.zhouzhaodong.xyz/archives/cache
正文到此结束
Loading...