需求: 因为会使用到Spring-redis作为缓存框架缓存数据,不让程序每次查询都进到数据库中,因此正对不同的数据格式需要进行序列化和反序列化,于是就自己实现了一个简单的序列化类
首先 配置 Springboot 的 redis 配置
# REDIS (RedisProperties) # Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=192.168.0.11 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password=ThisIsPass # 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=-1 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 # 连接池中的最大空闲连接 spring.redis.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.pool.min-idle=2 # 连接超时时间(毫秒) spring.redis.timeout=50
接下来实现 序列化类 (这里使用到了GSON):
import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; public class RedisValueSerializer<T> implements RedisSerializer<T> { private static final byte[] EMPTY_ARRAY = new byte[0]; @Override public byte[] serialize(T t) throws SerializationException { if (t == null) { return EMPTY_ARRAY; } String tmp = String.format("%s_%s", t.getClass().getName(), JsonUtils.obj2Json(t)); return tmp.getBytes(Encode.UTF8); } @Override public T deserialize(byte[] bytes) throws SerializationException { try { if (bytes == null || bytes.length <= 0) { return null; } String tmp = new String(bytes, Encode.UTF8); String className = tmp.substring(0, tmp.indexOf("_{")); String json = tmp.substring(tmp.indexOf("_{") + 1); return (T) JsonUtils.json2Obj(json, Class.forName(className)); } catch (ClassNotFoundException ex) { LogUtils.error(TAG.DEF, this.getClass(), "deserialize", ex); } return null; } }
然后RedisConfig:
import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; 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; @Primary @Configuration public class RedisConfig extends CachingConfigurerSupport { @Primary @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); return rcm; } @Primary @Bean public StringRedisTemplate redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); template.setValueSerializer(new RedisValueSerializer<Object>()); template.afterPropertiesSet(); return template; } }
然后就可以使用缓存注解了:
@Cacheable(key ="#p0") @CachePut(key = "#p0") @CacheEvict(key ="#p0",allEntries=true) ...
注解使用参考:http://blog.csdn.net/sanjay_f/article/details/47372967