SpringBoot缓存使用Redis与@CaChe注解整合 简洁使用

一、配置

1.引入redis jar包

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.springboot集成redis写配置,application.properties

spring:
  redis:
    database: 0 # Database index used by the connection factory.
    url: redis://user:@127.0.0.1:6379 # Connection URL. Overrides host, port, and password. User is ignored. Example: redis://user:password@example.com:6379
    host: 127.0.0.1 # Redis server host.
    password: # Login password of the redis server.
    port: 6379 # Redis server port.
    ssl: false # Whether to enable SSL support.
    timeout: 5000 # Connection timeout.

3.编写配置类 RedisCacheConfig.java

package xx;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;


@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration
                .defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                // 可以给每个cacheName不同的RedisCacheConfiguration  设置不同的过期时间
                //.withCacheConfiguration("Users",config.entryTtl(Duration.ofSeconds(100)))
                .transactionAware()
                .build();
        return cacheManager;
    }


}

二、使用

在启动类加上开启缓存的注解 @EnableCaching , 其它注解写在业务层

1.写入缓存 @CachePut

在这里插入图片描述

代码说明:将系统code实体类放入缓存为systemIdCache中,key为系统编码,状态为1时新增

/**新增与更新数据**/
    @Override
    @CachePut(value = "systemIdCache", key = "#record.sysCode", condition = "#result.status eq 1")
    public SystemIdDto insertAndUpdateSelective(SystemIdDto record){    
        systemIdDao.insertAndUpdateSelective(record);
        return record;
    }

2.读取缓存 @Cacheable

在这里插入图片描述
代码说明:读取存储名称为systemIdCache,key为sysCode值的数据,查找不到时,将会执行此查询方法,再将查询出的数据存入缓存中

/**根据系统code查询*/
    @Override
    @Cacheable(value = "systemIdCache",key = "#sysCode")
    public SystemIdDto selectBySysCode(String sysCode) {
        SystemIdDto dto = new SystemIdDto();
        dto.setSysCode(sysCode);
        dto.setStatus(SystemIdDto.Status.YouXiao);
        SystemIdDto dto = systemIdDao.selectBySysCode(dto);
        return dto ;
    }

3.删除缓存 @CacheEvict

在这里插入图片描述
代码说明:方法代码写的是逻辑删除,修改状态为无效,注解@CacheEvice删除sysCode为key的缓存,且在这个方法执行前删除

  /**根据主键删除**/
    @Override
    @CacheEvict(value="systemIdCache",key = "#record.sysCode", beforeInvocation=true)
    public CommonResp<String> deleteById(SystemIdDto record){
        record.setStatus(SystemIdDto.Status.WuXiao);
        systemIdDao.updateById(record);
        return CommonRespBuild.Success;
    }

4.注解配置 @CacheConfig

新增/读取/删除 例子中 所有注解的value属性都是同一个,为了方便,我们可以将它提取出来。

 /**使用@CacheConfig注解将公共提取出来,
   *整个类的cache注解都公用这个属性,
   *其他方法不使用仍可覆盖*/
@Service
@CacheConfig(cacheNames = "systemIdCache")
public class SystemIdServiceImpl implements SystemIdService {

	/**根据系统code查询*/
	//公用缓存名称
    @Override
    @Cacheable(key = "#sysCode")
    public SystemIdDto selectBySysCode(String sysCode) {
        SystemIdDto dto = new SystemIdDto();
        dto.setSysCode(sysCode);
        dto.setStatus(SystemIdDto.Status.YouXiao);
        SystemIdDto dto = systemIdDao.selectBySysCode(dto);
        return dto ;
    }
    
	  /**根据主键删除**/
	  //不使用公用缓存名称
    @Override
    @CacheEvict(value="systemIdCache1",key = "#record.sysCode", beforeInvocation=true)
    public CommonResp<String> deleteById(SystemIdDto record){
        record.setStatus(SystemIdDto.Status.WuXiao);
        systemIdDao.updateById(record);
        return CommonRespBuild.Success;
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值