Springboot Mybatis 集成 Redis

版本信息

  1. Sprintboot 採用 2.1.7 RELEASE 版本
  2. Mybatis 採用 2.1.0
  3. Redis 採用 2.1.6.RELEASE

Redis 的使用

  1. 添加 Redis 依賴java

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
      <version>2.1.6.RELEASE</version>
    </dependency>
  2. 開啓緩存git

    @SpringBootApplication
    @EnableCaching
    public class HelloApplication {
        public static void main(String[] args) {
            SpringApplication.run(HelloApplication.class, args);
        }
    }
    • 使用註解 @EnableCaching 開啓緩存
  3. 添加緩存註解github

    @Override
        @Cacheable(value = "UserCache", key = "'user.getAllUsers'")
        public List<User> getAllUsers() {
            return userMapper.getAllUsers();
        }
    • 在業務邏輯類的方法上添加 @Cacheable 註解來支持緩存
    • @Cacheable 註解中的 key 屬性值除了須要被英文雙引號引用外,還須要加入英文單引號
  4. Bean 實現序列化redis

    public class User implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        private Integer id;
        private String username;
        private String address;
    
        public User() {
    
        }
    
        public User(Integer id, String username, String address) {
            this.id = id;
            this.username = username;
            this.address = address;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username == null ? "" : username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getAddress() {
            return address == null ? "" : address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    }
  5. 指定 Redis 緩存地址spring

    redis:
        host: localhost
        port: 6379
    • 在 Application.yml 文件指定 Redis 的地址和端口號
  6. 清除 Redis 緩存
    java @Override @CacheEvict(value = "UserCache", key = "'user.getAllUsers'") public void delete(Integer id) { System.out.println("刪除了 id 爲" + id + "的用戶"); userMapper.delete(id); }
    • 當刪除了數據庫的數據的時候,對 Redis 中緩存的數據進行清除。
    • @CacheEvict 註解,與 @Cacheable 註解配置徹底相同
  7. 啓動項目測試緩存數據庫

源碼地址: github緩存

相關文章
相關標籤/搜索