redis Jedis序列化自定义存储list对象和map数据

1,redis缓存配置类
public class RedisCache {
protected static Logger logger = Logger.getLogger(RedisCache.class);
public final static String VIRTUAL_COURSE_PREX = "_lc_vc_";


private RedisCacheConfig redisCacheConfig;
private JedisPool jedisPool = null;

public RedisCacheConfig getRedisCacheConfig() {
return redisCacheConfig;
}

public void setRedisCacheConfig(RedisCacheConfig redisCacheConfig) {
this.redisCacheConfig = redisCacheConfig;
}

public RedisCache(){

}

/**
* 初始化Redis连接池
*/
private void initialPool(){
JedisPoolConfig poolConfig = redisCacheConfig.getPoolConfig();
String[] serverArray = redisCacheConfig.getServers().split(",");
for(int i = 0; i < serverArray.length; i++){
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(poolConfig.getMaxTotal());
config.setMaxIdle(poolConfig.getMaxIdle());
config.setMaxWaitMillis(poolConfig.getMaxWaitMillis());
config.setTestOnBorrow(poolConfig.getTestOnBorrow());
config.setTestOnReturn(poolConfig.getTestOnReturn());

jedisPool = new JedisPool(config, serverArray[i], redisCacheConfig.getPort(), redisCacheConfig.getTimeout());
break;
} catch (Exception e) {
logger.error("initialPool create JedisPool(" + serverArray[i] + ") error : "+e);
}
}

}

/**
* 在多线程环境同步初始化
*/
private synchronized void poolInit() {
if (jedisPool == null) {
initialPool();
}
}


/**
* 同步获取Jedis实例
* @return Jedis
*/
public synchronized Jedis getJedis() {
if (jedisPool == null) {
poolInit();
}
Jedis jedis = null;
try {
if (jedisPool != null) {
jedis = jedisPool.getResource();
jedis.auth(redisCacheConfig.getAuth());
}
} catch (Exception e) {
logger.error("Get jedis error : "+e);
e.printStackTrace();
}finally{
returnResource(jedis);
}
return jedis;
}

/**
* 释放jedis资源
* @param jedis
*/
public void returnResource(final Jedis jedis) {
if (jedis != null && jedisPool !=null) {
jedisPool.returnResource(jedis);
}
}

/**
* 得到Key
* @param key
* @return
*/
public String buildKey(String key){
return VIRTUAL_COURSE_PREX + key;
}
/**
* 设置 String
* @param key
* @param value
*/
public void setString(String key ,String value){
try {
value = StringUtil.isNullOrEmpty(value) ? "" : value;
getJedis().set(buildKey(key),value);
} catch (Exception e) {
logger.error("Set key error : "+e);
}
}

/**
* 设置 过期时间
* @param key
* @param seconds 以秒为单位
* @param value
*/
public void setString(String key ,int seconds,String value){
try {
value = StringUtil.isNullOrEmpty(value) ? "" : value;
getJedis().setex(buildKey(key), seconds, value);
} catch (Exception e) {
logger.error("Set keyex error : "+e);
}
}

/**
* 获取String值
* @param key
* @return value
*/
public String getString(String key){
String bKey = buildKey(key);
if(getJedis() == null || !getJedis().exists(bKey)){
return null;
}
return getJedis().get(bKey);
}
/**
* 设置 list
* @param <T>
* @param key
* @param value
*/
public <T> void setList(String key ,List<T> list){
try {
getJedis().set(key.getBytes(),ObjectTranscoder.serialize(list));
} catch (Exception e) {
logger.error("Set key error : "+e);
}
}
/**
* 获取list
* @param <T>
* @param key
* @return list
*/
public <T> List<T> getList(String key){
String bKey = buildKey(key);
if(getJedis() == null || !getJedis().exists(key.getBytes())){
return null;
}
byte[] in = getJedis().get(key.getBytes());
List<T> list = (List<T>) ObjectTranscoder.deserialize(in);
return list;
}
/**
* 设置 map
* @param <T>
* @param key
* @param value
*/
public <T> void setMap(String key ,Map<String,T> map){
try {
getJedis().set(key.getBytes(),ObjectTranscoder.serialize(map));
} catch (Exception e) {
logger.error("Set key error : "+e);
}
}
/**
* 获取list
* @param <T>
* @param key
* @return list
*/
public <T> Map<String,T> getMap(String key){
String bKey = buildKey(key);
if(getJedis() == null || !getJedis().exists(key.getBytes())){
return null;
}
byte[] in = getJedis().get(key.getBytes());
Map<String,T> map = (Map<String, T>) ObjectTranscoder.deserialize(in);
return map;
}
}

2,spring配置

<!-- 声明redisCache -->
<bean id="redisCache" class="com.cache.RedisCache" depends-on="redisCacheConfig">
<property name="redisCacheConfig" ref="redisCacheConfig"></property>
</bean>
<bean id="redisCacheConfig" class="com.able.virtualcourse.cache.RedisCacheConfig" depends-on="jedisPoolConfig">
<property name="servers"><value>${redis.servers}</value></property>
<property name="port"><value>${redis.port}</value></property>
<property name="auth"><value>${redis.auth}</value></property>
<property name="timeout"><value>${redis.pool.timeout}</value></property>
<property name="poolConfig" ref="jedisPoolConfig"></property>
</bean>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal"><value>${redis.pool.maxTotal}</value></property>
<property name="maxIdle"><value>${redis.pool.maxIdle}</value></property>
<property name="maxWaitMillis"><value>${redis.pool.maxWait}</value></property>
<property name="testOnBorrow"><value>${redis.pool.testOnBorrow}</value></property>
<property name="testOnReturn"><value>${redis.pool.testOnReturn}</value></property>
</bean>

3,序列化工具类

public class ObjectTranscoder {
public static byte[] serialize(Object value) {
if (value == null) {
throw new NullPointerException("Can't serialize null");
}
byte[] rv=null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
os.writeObject(value);
os.close();
bos.close();
rv = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
try {
if(os!=null)os.close();
if(bos!=null)bos.close();
}catch (Exception e2) {
e2.printStackTrace();
}
}
return rv;
}

public static Object deserialize(byte[] in) {
Object rv=null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if(in != null) {
bis=new ByteArrayInputStream(in);
is=new ObjectInputStream(bis);
rv=is.readObject();
is.close();
bis.close();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(is!=null)is.close();
if(bis!=null)bis.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return rv;
}
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了与Redis的集成支持,可以通过配置和使用Spring Data Redis来实现。下面是整合Redis并实现自定义序列化的步骤: 1. 添加依赖:在`pom.xml`文件中添加Spring Data Redis的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis连接信息:在`application.properties`或`application.yml`文件中配置Redis的连接信息,例如: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 3. 创建Redis配置类:创建一个配置类,用于配置Redis连接工厂和RedisTemplate等相关配置。可以参考以下示例: ```java @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean public RedisConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(); config.setHostName("127.0.0.1"); config.setPort(6379); return new LettuceConnectionFactory(config); } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } ``` 在上述示例中,我们使用了Lettuce作为Redis的连接工厂,并设置了默认的序列化器为`GenericJackson2JsonRedisSerializer`,这样可以将对象以JSON格式进行序列化和反序列化。 4. 实现自定义序列化:如果需要自定义序列化方式,可以创建一个实现了`RedisSerializer`接口的自定义序列化器。例如,我们可以创建一个自定义的JSON序列化器: ```java public class CustomJsonRedisSerializer<T> implements RedisSerializer<T> { private final ObjectMapper objectMapper; public CustomJsonRedisSerializer() { this.objectMapper = new ObjectMapper(); this.objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); this.objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); } @Override public byte[] serialize(T t) throws SerializationException { if (t == null) { return new byte; } try { return objectMapper.writeValueAsBytes(t); } catch (JsonProcessingException e) { throw new SerializationException("Error serializing object to JSON: " + e.getMessage(), e); } } @Override public T deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length == 0) { return null; } try { return objectMapper.readValue(bytes, new TypeReference<T>() {}); } catch (IOException e) { throw new SerializationException("Error deserializing object from JSON: " + e.getMessage(), e); } } } ``` 在上述示例中,我们使用了Jackson库来进行JSON的序列化和反序列化。 5. 使用自定义序列化器:在Redis配置类中,将自定义序列化设置RedisTemplate的序列化器: ```java @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { // ... @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); template.setDefaultSerializer(new CustomJsonRedisSerializer<>()); return template; } } ``` 通过以上步骤,你就可以实现Spring Boot与Redis的整合,并使用自定义序列化器来对对象进行序列化和反序列化了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值