springboot2.x+redis整合
2019-01-12 19:19
525 查看
1.依赖
[code]<!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
2.RedisConfig配置
/** * <> * <Redis配置> * * @Author jason_w * @Date 2019/1/8 0008 22:10 * @see */ @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { /** * 生成key的策略 * @return */ @Bean public KeyGenerator KeyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } /** * 管理缓存 */ @Bean CacheManager cacheManager(RedisConnectionFactory connectionFactory) { RedisCacheConfiguration cacheConfiguration =RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(10L))//缓存10秒 .disableCachingNullValues().computePrefixWith(cacheName -> "Shiro".concat(":").concat(":")) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); // 设置一个初始化的缓存空间set集合 Set<String> cacheNames = new HashSet<>(); cacheNames.add("Shiro"); cacheNames.add("user"); // 对每个缓存空间应用不同的配置 Map<String, RedisCacheConfiguration> configMap = new HashMap<>(); configMap.put("Shiro", cacheConfiguration); configMap.put("user", cacheConfiguration.entryTtl(Duration.ofSeconds(10))); // 使用自定义的缓存配置初始化一个cacheManager RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory) // 注意这两句的调用顺序,一定要先调用该方法设置初始化的缓存名,再初始化相关的配置 .initialCacheNames(cacheNames) .withInitialCacheConfigurations(configMap) .build(); return cacheManager; } /** * RedisTemplate配置 */ @Bean @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(factory); 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); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
3.application.properties配置redis
[code]# REDIS(RedisProperties) # (普通集群,不使用则不用开启)在群集中执行命令时要遵循的最大重定向数目。 # spring.redis.cluster.max-redirects= # (普通集群,不使用则不用开启)以逗号分隔的“主机:端口”对列表进行引导。 # spring.redis.cluster.nodes= # 连接工厂使用的数据库索引。 spring.redis.database=0 # 连接URL,将覆盖主机,端口和密码(用户将被忽略),例如:redis://user:password@example.com:6379 #spring.redis.url= # Redis服务器主机。 spring.redis.host=localhost # 登录redis服务器的密码。 spring.redis.password= # 启用SSL支持。 spring.redis.ssl=false # 池在给定时间可以分配的最大连接数。使用负值无限制。 spring.redis.jedis.pool.max-active=8 # 池中“空闲”连接的最大数量。使用负值表示无限数量的空闲连接。 spring.redis.jedis.pool.max-idle=8 # 连接分配在池被耗尽时抛出异常之前应该阻塞的最长时间量(以毫秒为单位)。使用负值可以无限期地阻止。 spring.redis.jedis.pool.max-wait=-1ms # 目标为保持在池中的最小空闲连接数。这个设置只有在正面的情况下才有效果。 spring.redis.jedis.pool.min-idle=0 # Redis服务器端口。 spring.redis.port=6379 # (哨兵模式,不使用则不用开启)Redis服务器的名称。 # spring.redis.sentinel.master= # (哨兵模式,不使用则不用开启)主机:端口对的逗号分隔列表。 # spring.redis.sentinel.nodes= # 以毫秒为单位的连接超时。 spring.redis.timeout=0ms
4.开启缓存注解
[code]@SpringBootApplication @EnableCaching//开启缓存 public class SpearWebApplication { public static void main(String[] args) { SpringApplication.run(SpearWebApplication.class, args); } }
5.注解用法
[code]@Cacheable(cacheNames = "RoleService",key ="#userName") @Override public List<String> queryRoleNameByUserName(String userName) { List<String> stringList=new ArrayList<>(); List<Role> maps = roleRepository.queryRoleNameByUserName(userName); for (Role map : maps) { stringList.add(map.getRoleName()); } return stringList; }
6.和shiro组合注意点
shiro和cache在引用service实例顺序问题,shiro引入应在cache后,
shiro配置文件中引用realm属性bean中引用的service采用延迟加载策略。
@Autowired
@Lazy
private UserServiceI userService;
相关文章推荐
- Springboot 2.X中Spring-cache与redis整合
- Spring Boot 2.x整合Redis
- Springboot 2.X与redis整合
- SpringBoot2.X 整合RedisTemplate 简单实现消息队列
- 记一次springboot2.x以上整合redis 库与库之间的切换个入的坑
- SpringBoot系列十:SpringBoot整合Redis
- 在Springboot中整合Ehcache以及整合Redis
- Spring Boot+Shiro+Redis(redisson)整合时,采用内嵌tomcat启动错误原因分析
- SpringCloud SpringBoot mybatis 分布式微服务(二十四)整合Redis
- Spring Boot 整合 Redis 实现缓存操作
- springboot整合redis
- Springboot整合redis的坑
- Spring Boot---(6)SpringBoot整合Redis
- SpringBoot 整合Redis 数据库的方法
- 整合spring-boot-starter-data-redis报错解决
- springBoot、Mabatis、Redis整合
- SpringBoot整合Redis集群
- springboot同时整合redis和ehcache
- Spring Boot+Shiro+Redis(redisson)整合时,采用内嵌tomcat启动错误原因分析
- Spring Boot学习之整合Redis实现缓存