介绍SpringBoot 整合 Redis 缓存
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version></dependency>2.在application.properties配置信息
#Redis数据库索引(默认为0)spring.redis.database=0#Redis服务器地址spring.redis.host=localhost#Redis服务器连接端口spring.redis.port=6379#Redis服务器连接密码(默认为空)spring.redis.password=123456#连接池最大连接数(使用负值表示没有限制)spring.redis.pool.max-active=200#连接池最大阻塞等待时间(使用负值表示没有限制)spring.redis.pool.max-wait=-1#连接池中的最大空闲连接spring.redis.pool.max-idle=10#连接池中的最小空闲连接spring.redis.pool.min-idle=0#连接超时时间(毫秒)spring.redis.timeout=1000ms3.编写Redis工具类
@Configuration@ConditionalOnClass(RedisOperations.class)//系统中有RedisOperations类时@EnableConfigurationProperties(RedisProperties.class)//启动RedisProperties这个类@EnableCaching//www.1b23.compublicclassRedisConfigextendsCachingConfigurerSupport{@AutowiredRedisTemplateredisTemplate;//配置缓存管理器@BeanpublicRedisCacheManagercacheManager(RedisConnectionFactoryconnectionFactory){LettuceConnectionFactoryjedisConnectionFactory=(LettuceConnectionFactory)redisTemplate.getConnectionFactory();jedisConnectionFactory.setDatabase(2);//指定dbindexredisTemplate.setConnectionFactory(jedisConnectionFactory);jedisConnectionFactory.resetConnection();RedisCacheConfigurationconfig=RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(60*20))//20分钟缓存失效//设置key的序列化方式//.entryTtl(Duration.ofSeconds(10)).serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(newStringRedisSerializer()))//设置value的序列化方式.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(newFastJsonRedisSerializer(Object.class)))//不缓存null值.disableCachingNullValues();RedisCacheManagerredisCacheManager=RedisCacheManager.builder(connectionFactory).cacheDefaults(config).transactionAware().build();returnredisCacheManager;}}
packagecom.FireService.config;importjava.nio.charset.Charset;importorg.springframework.data.redis.serializer.RedisSerializer;importorg.springframework.data.redis.serializer.SerializationException;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.parser.ParserConfig;importcom.alibaba.fastjson.serializer.SerializerFeature;publicclassFastJsonRedisSerializer<T>implementsRedisSerializer<T>{publicstaticfinalCharsetDEFAULT_CHARSET=Charset.forName("UTF-8");privateClass<T>clazz;static{ParserConfig.getGlobalInstance().addAccept("com.FireService");}publicFastJsonRedisSerializer(Class<T>clazz){super();this.clazz=clazz;}@Overridepublicbyte[]serialize(Tt)throwsSerializationException{if(null==t){returnnewbyte[0];}returnJSON.toJSONString(t,SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);}@OverridepublicTdeserialize(byte[]bytes)throwsSerializationException{if(null==bytes||bytes.length<=0){returnnull;}Stringstr=newString(bytes,DEFAULT_CHARSET);return(T)JSON.parseObject(str,clazz);}}4.SpringBoot有关缓存的几个注解
@Cacheable:查询
可选属性:
cacheNames/value:指定缓存组件的名字;
key:缓存数据使用的key,可以用来指定。默认即使用方法参数的值
keyGenerator:key的生成器,可以自己指定key的生成器的组件id
//自定义配置类配置keyGenerator@ConfigurationpublicclassMyCacheConfig{@Bean("myKeyGenerator")publicKeyGeneratorkeyGenerator(){returnnewKeyGenerator(){@OverridepublicObjectgenerate(Objecttarget,Methodmethod,Object...params){returnmethod.getName()+"["+Arrays.asList(params).toString()+"]";}};}}
cacheManager:指定缓存管理器;或者cacheResolver获取指定解析器
condition:指定符合条件的情况下才缓存;如condition="#id>0"
unless:否定缓存,当unless指定的条件为true,方法的返回值不会被缓存,可以获取到结果进行判断;如unless="#result==null";
sync:是否使用异步模式
例如:
@Cacheable(value="RedisInfo",key="#root.methodName+'['+#account+']'")@ResponseBody@RequestMapping("/RedisTest")publicResultfindUserOrder(Stringaccount)throwsException{if(account!=null){List<Map<String,Object>>list=orderFindGoods.findUserOrder(account);returnResults.successWithData(list,BaseEnums.SUCCESS.code(),BaseEnums.SUCCESS.desc());}else{returnResults.failure();}}
运行项目查看结果
1.第一次访问
查看Druid连接信息
原文地址:https://www.linuxprobe.com/springbootredis.html
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。