Spring-Data-Redis存储对象(redisTemplate)

先看实例:

...
    @Autowired
    RedisTemplate redisTemplate;

    public void testGetUserByName(){
        User user = new User();
        user.setUserName("用户1");
        redisTemplate.opsForValue().set("user1", user);
        Assert.assertEquals(user.getUserName(), ((User) jedisClient.get("user1")).getUserName());
    }
//User已经实现了Serializable接口
//配置的是org.springframework.data.redis.serializer.StringRedisSerializer
...

使用StringRedisSerializer直接缓存Object会出现转换错误:

java.lang.ClassCastException: dev.entity.User cannot be cast to java.lang.String

    at org.springframework.data.redis.serializer.StringRedisSerializer.serialize(StringRedisSerializer.java:32)
    at org.springframework.data.redis.core.AbstractOperations.rawValue(AbstractOperations.java:112)
    at org.springframework.data.redis.core.DefaultValueOperations.set(DefaultValueOperations.java:168)
    at dev.dao.RedisTest.testGetUserByName(RedisTest.java:22)
...

解决方法

StringRedisTemplate相当于RedisTemplate<String, String>的实现。
缓存时需要把Object类转为byte[]再存到redis中,反之要从redis中获取byte[]再转成Object。

看了很多人的实现方法,感觉这个实现最优雅便捷。最主要的转换代码如下:

    /**
     * 描述 : <byte[]转Object>. <br>
     * <p>
     * <使用方法说明>
     * </p>
     *
     * @param bytes
     * @return
     */
    private Object toObject(byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return obj;
    }
 
    private byte[] toByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }
}

相当于封装了一个处理Object缓存的类,之后用这个类与redis做交流。

package dev.dao;

import dev.cache.JedisClient;
import dev.entity.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/spring/spring-redis.xml")
public class RedisTest {
    @Autowired
    JedisClient jedisClient;

    @Test
    public void testGetUserByName(){
        User user = new User();
        user.setUserName("用户1");
        jedisClient.put("user1", user);

        Assert.assertEquals(user.getUserName(), ((User) jedisClient.get("user1")).getUserName());
    }
}

//测试成功
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,316评论 19 139
  • (一)Java部分 1、列举出JAVA中6个比较常用的包【天威诚信面试题】 【参考答案】 java.lang;ja...
    独云阅读 7,228评论 0 62
  • 本文完全参照并抄写了翟永超博客: Spring Cloud构建微服务架构(五)服务网关 服务网关是微服务架构中一个...
    WeiminSun阅读 916评论 0 2
  • 冥冥中往昔, 遗忘的恭喜。 有谁来斧劈, 太阳的鼻息, 厚葬这风景。 嗯,就这样。 焦虑懦弱,我为荣耀而归。 我,...
    闫慧龙阅读 190评论 0 0
  • 致敬爱的老师: 张德芬在《遇见未知的自己》里写道:“如果一个人充满了快乐、正面的思想,那么好的人,事、物都会和他...
    杯子君阅读 681评论 0 5

友情链接更多精彩内容