1:、引入spring-boot-starter-data-redis 和 spring-boot-starter-cache
org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-cache
2、配置application.yml
##### Redis 配置 spring: redis: database: 3 host: 127.0.0.1 port: 6379 password: ENC(InC5Jf51Km/w1hMzik2ej83hZqHAg+bU) timeout: 6000 jedis: pool: max-active: 200 max-idle: 100 max-wait: 1000 min-idle: 50
3. 缓存配置类
import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.cache.RedisCacheWriter; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import java.time.Duration; import java.util.HashMap; import java.util.Map; /** * 缓存配置类 * @author zhoujin */ @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport { protected final static Logger log = LoggerFactory.getLogger(RedisCacheConfig.class); //redis 缓存默认过期时间单位:秒 private static final Long DEFAULT_EXPIRATION_TIME = 600L; @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { return new RedisCacheManager( RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), // 默认策略,@Cacheable未配置的 key 会使用这个,默认过期时间 this.getRedisCacheConfigurationWithTtl(DEFAULT_EXPIRATION_TIME), // @Cacheable 指定 key 策略 this.getRedisCacheConfigurationMap() ); } private MapgetRedisCacheConfigurationMap() { Map redisCacheConfigurationMap = new HashMap<>(); redisCacheConfigurationMap.put("testRedisCache", this.getRedisCacheConfigurationWithTtl(3000L)); redisCacheConfigurationMap.put("UserInfoListAnother", this.getRedisCacheConfigurationWithTtl(18000L)); return redisCacheConfigurationMap; } private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Long seconds) { // 设置CacheManager的值序列化方式为JdkSerializationRedisSerializer, // 但其实RedisCacheConfiguration默认就是使用StringRedisSerializer序列化key,JdkSerializationRedisSerializer序列化value ClassLoader loader = this.getClass().getClassLoader(); JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer(loader); RedisSerializationContext.SerializationPair
4. 封装redisTemplate 工具类
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Redis Util * @author zhouJin * @date 2018年10月29日 */ @Component public class RedisCacheHelper { private Logger logger = LoggerFactory.getLogger(getClass()); //注: 这里不能用Autowired按类型装配注入,必须用@Resource // StringRedisTemplate默认采用的是String的序列化策略, // RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的 @Resource private RedisTemplateredisTemplate; /** * 指定缓存失效时间 * @param key 键 * @param time 时间(秒) * @return */ public boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Throwable e) { logger.error("redis操作异常:",e); return false; } } /** * 根据key 获取过期时间 * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 判断key是否存在 * @param key 键 * @return true 存在 false不存在 */ public boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Throwable e) { logger.error("redis操作异常:",e); return false; } } /** * 删除缓存 * @param key 可以传一个值 或多个 */ @SuppressWarnings("unchecked") public void del(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete(CollectionUtils.arrayToList(key)); } } } // ============================String============================= /** * 普通缓存获取 * @param key 键 * @return 值 */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * 普通缓存放入 * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Throwable e) { logger.error("redis操作异常:",e); return false; } } /** * 普通缓存放入并设置时间 * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * @return true成功 false 失败 */ public boolean set(String key, Object value, long time) { try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Throwable e) { logger.error("redis操作异常:",e); return false; } } /** * 递增 * @param key * @param delta 要增加几(大于0) * @return */ public long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 * @param key 键 * @param delta 要减少几(小于0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } // ================================Map================================= /** * HashGet * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 获取hashKey对应的所有键值 * @param key 键 * @return 对应的多个键值 */ public Map