spring boot集成redis使用@Cacheable等注解为接口添加缓存

缓存处理方式应该是

  1. 先从缓存中拿数据,如果有,直接返回。
  2. 如果拿到的为空,则数据库查询,然后将查询结果存到缓存中。

由此实现方式应该如下:

   private String baseKey = "category";

    public CmfCategories selectByPrimaryKey(Long id) {
        //1. 先从缓存中取
        CmfCategories cmfCategories = redisUtils.get(baseKey + id, CmfCategories.class);
        if (cmfCategories == null) {    //如果取值为空
            //2. 从数据中查询
            cmfCategories = cmfCategoriesMapper.selectByPrimaryKey(id);
            //3. 将查询结果存入缓存
            redisUtils.set(baseKey + id, cmfCategories, DEFAULT_EXPIRE * 7);
        }
        return cmfCategories;
    }

这种方式是没错的,但就是实现起来,每个接口都要做一遍重复的操作,下面演示一种简洁的使用注解实现方式:

    @Cacheable(value = "newsCategory", key = "'newsCategory:'+#id", unless = "#result==null")
    public CmfCategories selectByPrimaryKey(Long id) {
        return cmfCategoriesMapper.selectByPrimaryKey(id);
    }

明显简单多了,而且**对代码无侵入**!

实现步骤

  1. 添加maven依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
  1. 添加配置

/**
 * Redis缓存配置。
 */
@Configuration
@EnableCaching
public class RedisCacheConfig {

    @Autowired
    private RedisConnectionFactory factory;

    @Bean
    public CacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
        // 默认缓存一天 86400秒
        redisCacheManager.setDefaultExpiration(86400L);
        return redisCacheManager;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        // 字符串Key序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        // 对象值序列化
        ObjectRedisSerializer objectRedisSerializer = new ObjectRedisSerializer();
        redisTemplate.setValueSerializer(objectRedisSerializer);
        redisTemplate.setHashValueSerializer(objectRedisSerializer);
        return redisTemplate;
    }



}
  1. 具体使用

在需要缓存的接口上添加注解

 @Cacheable(value = "newsCategory", key = "'newsCategory:'+#id", unless = "#result==null")
    public CmfCategories selectByPrimaryKey(Long id) {
        return cmfCategoriesMapper.selectByPrimaryKey(id);
    }

当被缓存的数据被更新的时候,可以使用@CacheEvict来清除缓存,则可以保证缓存的数据是最新的

@CacheEvict(value = "User", key = "'User:'+#userParam.userId", condition = "#userParam!=null")
    public long setUserBasicInfo(UserBasicInfo userParam, String token) {
        //do something
    }

简单讲解

参考链接

缓存数据

对于缓存的操作,主要有:@Cacheable、@CachePut、@CacheEvict。

  • @Cacheable

Spring 在执行 @Cacheable 标注的方法前先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,执行该方法并将方法返回值放进缓存。 参数: value缓存名、 key缓存键值、 condition满足缓存条件、unless否决缓存条件

@Cacheable(value = "user", key = "#id")  
public User findById(final Long id) {  
    System.out.println("cache miss, invoke find by id, id:" + id);  
    for (User user : users) {  
        if (user.getId().equals(id)) {  
            return user;  
        }  
    }  
    return null;  
} 
  • @CachePut

和 @Cacheable 类似,但会把方法的返回值放入缓存中, 主要用于数据新增和修改方法。

@CachePut(value = "user", key = "#user.id")  
public User save(User user) {  
    users.add(user);  
    return user;  
}  
  • @CacheEvict

方法执行成功后会从缓存中移除相应数据。 参数: value缓存名、 key缓存键值、 condition满足缓存条件、 unless否决缓存条件、 allEntries是否移除所有数据(设置为true时会移除所有缓存)

@CacheEvict(value = "user", key = "#user.id") // 移除指定key的数据  
public User delete(User user) {  
    users.remove(user);  
    return user;  
} 

@CacheEvict(value = "user", allEntries = true) // 移除所有数据  
public void deleteAll() {  
    users.clear();  
}  

  • 7
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Spring Boot是一个开发框架,它简化了使用Spring框架进行Java应用程序开发的过程。Redis是一个内存数据结构存储系统,它可以用作缓存和数据库。@CacheableSpring框架的注解之一,它可以用于缓存方法的返回值。 要在Spring Boot使用Redis和@Cacheable来实现缓存,首先需要配置Redis连接。可以通过在`application.properties`或`application.yml`文件中添加以下配置来完成: ```yaml spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 接下来,在需要缓存的方法上使用`@Cacheable`注解。例如,假设我们有一个名为`getUserById`的方法,用于根据用户ID获取用户信息: ```java @Service public class UserService { @Cacheable(value = "users", key = "#id") public User getUserById(Long id) { // 从数据库或其他数据源获取用户信息 return userRepository.findById(id); } } ``` 在上述示例中,`@Cacheable`注解用于将方法的返回值缓存起来。其中,`value`属性指定了缓存的名称,`key`属性指定了缓存的键。在这个例子中,缓存的名称为"users",缓存的键为方法的参数id。 最后,需要在Spring Boot应用程序的启动类上添加`@EnableCaching`注解来启用缓存功能: ```java @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 以上就是使用Spring BootRedis和@Cacheable实现缓存的基本步骤。通过配置Redis连接,使用`@Cacheable`注解来标记需要缓存的方法,并在启动类上添加`@EnableCaching`注解来启用缓存功能,可以轻松地实现缓存功能。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值