栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

​

一、配置
1.引入redis jar包

      org.springframework.boot
      spring-boot-starter-data-redis

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 redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        RedisSerializer 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 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值的数据,查找不到时,将会执行此查询方法,再将查询出的数据存入缓存中

    @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 deleteById(SystemIdDto record){
        record.setStatus(SystemIdDto.Status.WuXiao);
        systemIdDao.updateById(record);
        return CommonRespBuild.Success;
    }
4.注解配置 @CacheConfig

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

 
@Service
@CacheConfig(cacheNames = "systemIdCache")
public class SystemIdServiceImpl implements SystemIdService {

	
	//公用缓存名称
    @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 deleteById(SystemIdDto record){
        record.setStatus(SystemIdDto.Status.WuXiao);
        systemIdDao.updateById(record);
        return CommonRespBuild.Success;
    }
}

​

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/988211.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号