Springboot集成redis非常简单,如下,作者指出一种简单的实现方式
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import java.lang.reflect.Method; @Configuration @EnableCaching public class DspRedisConfig { @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(); } }; } @SuppressWarnings("rawtypes") @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); //设置缓存过期时间,对通过redisTemplate操作的redis无效 //rcm.setDefaultExpiration(300); return rcm; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(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); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
springboot核心的application文件添加如下配置
spring.redis.host = localhost spring.redis.port = 6379 spring.redis.pool.max-active = 20 spring.redis.pool.max-idle = 5 spring.redis.pool.min-idle = 0 spring.redis.pool.max-wait = 10000这样,当Springboot自动加载时候,就会把控制操作redis的redisTemplete注入
这样就可以通过注解方式操作我们要缓存的数据了
但是当我们想要独自去操作redisTemplete时,直接使用redisTemplete缓存数据时无效
作者修改代码如下,即可随意操作redis,过期时间在这里设置是管用的~~~~~~~~~
我设置的24小时过期的token~~~~~~~~~~~~~~~~~
package com.nox.dsp.utils; import com.nox.dsp.config.DspErrorConstant; import com.nox.dsp.config.DspServerConstant; import com.nox.dsp.entity.DspException; import com.nox.dsp.entity.DspResponseEntity; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.UUID; import java.util.concurrent.TimeUnit; @Service("tokenManager") public class TokenManager { private static Logger logger = LogManager .getLogger(TokenManager.class.getName()); @Autowired public RedisTemplate redisTemplate; public boolean genUserToken(DspResponseEntity repEntity) throws DspException { boolean isOk = false; try { if (!DspServerConstant.TOKEN_IS_CHECK) { return true; } String userToken = UUID.randomUUID().toString().replace("-", ""); String fullToken = DspServerConstant.TOKEN_PREFIX + "_" + repEntity.getCasEntity().getUid() + "_" + userToken; repEntity.getCasEntity().setUserToken(userToken); redisTemplate.opsForValue().set(fullToken ,DspServerConstant.TOKEN_VALUE); redisTemplate.expire(fullToken , 24*60*60 , TimeUnit.SECONDS); isOk = true; } catch (Exception e) { isOk = false; e.printStackTrace(); throw new DspException(DspErrorConstant.ERROR_100005, DspErrorConstant.ERROR_100005_MSG); } return isOk; } public Boolean checkUserToken(String uid, String userToken) { if (!DspServerConstant.TOKEN_IS_CHECK) { return true; } else if (uid == null || userToken == null) { return false; } else { String fullToken = DspServerConstant.TOKEN_PREFIX + "_" + uid + "_" + userToken; System.out.println(fullToken); Object value = redisTemplate.opsForValue().get(fullToken); if(value != null && value.equals("1")){ redisTemplate.delete(fullToken); return true; } return false; } } }