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

发布时间:2022-08-19 11:47

一、配置

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

SpringBoot缓存使用Redis与@CaChe注解整合 简洁使用_第1张图片

代码说明:将系统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

SpringBoot缓存使用Redis与@CaChe注解整合 简洁使用_第2张图片
代码说明:读取存储名称为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

SpringBoot缓存使用Redis与@CaChe注解整合 简洁使用_第3张图片
代码说明:方法代码写的是逻辑删除,修改状态为无效,注解@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;
    }
}

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号