标签:mamicode @param col coding names mes span nal list
一、建一个项目,勾选相关需要的依赖;
二、
1) 导入redis 依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2) 配置redis
a. 在springboot配置文件中配置redis的连接信息;
#配置数据源 spring: datasource: url: jdbc:mysql://localhost:3306/blog?userUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver redis: #单机 host: 192.168.190.141 port: 6379 lettuce: #连接池配置 pool: #连接池最大连接数 max-active: 20 #连接池最大等待时间,负数表示不做限制 max-wait: -1 #最大空闲连接 max-idle: 9 #最小空闲连接 min-idle: 0 server: #tomcat端口号 port: 8888 #mybatis 配置 mybatis: mapper-locations: classpath:mapper/*.xml
b. Springboot 新建一个配置类,配置redisTemplate;
@Configuration @EnableAutoConfiguration @EnableCaching //设置开启注解缓存 public class RedisConfig { /** * 配置RedisTemplate对象 * 指定对象的序列化方式 * * @param redisConnectionFactory * @return */ @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); redisTemplate.setConnectionFactory(redisConnectionFactory); //如果不配置Serializer,那么存储的时候缺省使用String,如果存储对象就会出现问题 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // key采用String的序列化方式 redisTemplate.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 redisTemplate.setHashKeySerializer(stringRedisSerializer); // valuevalue采用jackson序列化方式 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // hash的value采用jackson序列化方式 redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } /** * 配置缓存管理类,指定缓存的失效时间 * @param connectionFactory * @return */ @Bean CacheManager cacheManager(RedisConnectionFactory connectionFactory) { /* 默认配置, 默认超时时间为30s */ RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration .ofSeconds(3L*60))//指定默认的缓存时间 //设置key的序列化方式 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) //设置value的序列化方式 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); RedisCacheManager cacheManager = RedisCacheManager.builder(RedisCacheWriter.lockingRedisCacheWriter (connectionFactory)).cacheDefaults(defaultCacheConfig).transactionAware().build(); return cacheManager; } }
3) 使用redisTemplate 操作redisAPI 进行数据的读写操作;
RedisTemplate 常用API操作
1) opsForValue 操作String类型的数据
a. Set
b. Get
2) opsForSet :操作set类型数据
3) opsForList :操作List类型数据
4) opsForZset :操作ZSet类型数据
5) opsForHash :操作Hash类型数据
6) delete
@Service @Slf4j public class AdminServiceImpl implements AdminService { @Autowired private TAdminMapper tAdminMapper; //redisTemplate 为spring中对redis操作的对象 @Autowired private RedisTemplate redisTemplate; @Override public List<TAdmin> selectAll() { return tAdminMapper.selectByExample(new TAdminExample()); } @Override //缓存的实际key值为cacheNames:方法参数 @Cacheable(cacheNames = "adminCache") public TAdmin selectById(Integer id) { //1、去缓存中获取 //2、如果缓存中不存在,则数据库查询 //3、将查询的结果存入redis缓存 //4、返回结果 long start = System.currentTimeMillis(); TAdmin admin; if (redisTemplate.hasKey("admin:" + id)) { admin = (TAdmin) redisTemplate.opsForValue().get("admin:" + id); log.info("缓存中获取数据耗时:"+(System.currentTimeMillis()-start)); }else { start=System.currentTimeMillis(); admin=tAdminMapper.selectByPrimaryKey(id); log.info("从数据库中查询数据耗时:"+(System.currentTimeMillis()-start)); //设置String类型的数据,将查询的结果放入redis缓存,指定超时时间为10秒 redisTemplate.opsForValue().set("admin:"+id,admin,10, TimeUnit.SECONDS); } //删除key,如果对数据做了修改或删除操作,则需从缓存中删除对应数据 Boolean delete = redisTemplate.delete(id); //是否包含某个key Boolean aBoolean = redisTemplate.hasKey(id); //指定超时时间 redisTemplate.expire(id,10,TimeUnit.SECONDS); //设置在指定日期失效 redisTemplate.expireAt(id,new Date()); //获取对应的key值 Set keys = redisTemplate.keys("admin"); return admin; } @Override @Cacheable(cacheNames = "adminCache") public TAdmin selectByAccount(String account) { TAdminExample tAdminExample = new TAdminExample(); tAdminExample.createCriteria().andAccountEqualTo(account); List<TAdmin> tAdmins=tAdminMapper.selectByExample(tAdminExample); return tAdmins.size()>0?tAdmins.get(0):null; } @Override public int insert(TAdmin tAdmin) { return tAdminMapper.insert(tAdmin); } @Override //allEntries=true 表示删除adminCache下的所有缓存 //CacheEvict 删除对应的缓存 @CacheEvict(cacheNames = "adminCache",allEntries = true)//删除对应的缓存 public int delete(Integer id) { return tAdminMapper.deleteByPrimaryKey(id); } }
第二种方式:
使用注解的方式来使用redis缓存。
1) 配置开启缓存注解
@EnableCaching //设置开启注解缓存;
2) 配置默认的缓存策略;
/** * 配置缓存管理类,指定缓存的失效时间 * @param connectionFactory * @return */ @Bean CacheManager cacheManager(RedisConnectionFactory connectionFactory) { /* 默认配置, 默认超时时间为30s */ RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration .ofSeconds(3L*60))//指定默认的缓存时间 //设置key的序列化方式 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) //设置value的序列化方式 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); RedisCacheManager cacheManager = RedisCacheManager.builder(RedisCacheWriter.lockingRedisCacheWriter (connectionFactory)).cacheDefaults(defaultCacheConfig).transactionAware().build(); return cacheManager; }
3) 将缓存注解添加到需要的位置
a. @Cacheable 添加在需要缓存的方法上,会将方法的返回值存入缓存中;
b. @CacheEvict 删除缓存数据;
标签:mamicode @param col coding names mes span nal list
原文地址:https://www.cnblogs.com/xie-qi/p/13326623.html