<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>
# 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=1000ms
@Configuration @ConditionalOnClass(RedisOperations.class) //系統中有RedisOperations類時 @EnableConfigurationProperties(RedisProperties.class) //啓動RedisProperties這個類 @EnableCaching // www.1b23.com public class RedisConfig extends CachingConfigurerSupport { @Autowired RedisTemplate redisTemplate; // 配置緩存管理器 @Bean public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) { LettuceConnectionFactory jedisConnectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory(); jedisConnectionFactory.setDatabase(2); //指定dbindex redisTemplate.setConnectionFactory(jedisConnectionFactory); jedisConnectionFactory.resetConnection(); RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(60*20)) // 20分鐘緩存失效 // 設置key的序列化方式 // .entryTtl(Duration.ofSeconds(10)) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 設置value的序列化方式 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new FastJsonRedisSerializer(Object.class))) // 不緩存null值 .disableCachingNullValues(); RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory) .cacheDefaults(config) .transactionAware() .build(); return redisCacheManager; } }
package com.FireService.config; import java.nio.charset.Charset; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializerFeature; public class FastJsonRedisSerializer<T> implements RedisSerializer<T> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private Class<T> clazz; static { ParserConfig.getGlobalInstance().addAccept("com.FireService"); } public FastJsonRedisSerializer(Class<T> clazz) { super(); this.clazz = clazz; } @Override public byte[] serialize(T t) throws SerializationException { if (null == t) { return new byte[0]; } return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); } @Override public T deserialize(byte[] bytes) throws SerializationException { if (null == bytes || bytes.length <= 0) { return null; } String str = new String(bytes, DEFAULT_CHARSET); return (T) JSON.parseObject(str, clazz); } }
@Cacheable:查詢java
可選屬性:redis
cacheNames/value:指定緩存組件的名字;spring
key:緩存數據使用的key,能夠用來指定。默認即便用方法參數的值數據庫
keyGenerator:key的生成器,能夠本身指定key的生成器的組件idjson
//自定義配置類配置keyGenerator @Configuration public class MyCacheConfig { @Bean("myKeyGenerator") public KeyGenerator keyGenerator(){ return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { return method.getName()+"["+ Arrays.asList(params).toString() +"]"; } }; } }
cacheManager:指定緩存管理器;或者cacheResolver獲取指定解析器緩存
condition:指定符合條件的狀況下才緩存;如condition="#id>0"服務器
unless:否認緩存,當unless指定的條件爲true,方法的返回值不會被緩存,能夠獲取到結果進行判斷;如unless="#result==null";app
sync:是否使用異步模式less
例如:異步
@Cacheable(value = "RedisInfo", key = "#root.methodName+'['+#account+']'") @ResponseBody @RequestMapping("/RedisTest") public Result findUserOrder(String account) throws Exception{ if(account!=null) { List<Map<String, Object>> list=orderFindGoods.findUserOrder(account); return Results.successWithData(list, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc()); }else { return Results.failure(); } }
運行項目查看結果
1.第一次訪問
查看Druid鏈接信息