利用java将数据加入redis缓存

  1. } catch (JedisException e) {

  2. log.info("client can't connect server");

  3. if(null !=jedis){

  4. //redisUtil 对象

  5. redisUtil.brokenResource(jedis);

  6. }

  7. }

  8. return v;

  9. }

  10. @Override

  11. public Map<String, V> hget(String cacheKey,Object object) {

  12. JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象

  13. String jCacheKey = json.toString();//将json对象转换为字符串

  14. //非空校验

  15. if(StringUtils.isEmpty(jCacheKey)){

  16. log.info("cacheKey is empty!");

  17. return null;

  18. }

  19. Jedis jedis =null;

  20. Map<String,V> result =null;

  21. V v=null;

  22. try {

  23. jedis =redisUtil.getResource();

  24. //获取列表集合 因为插入redis的时候是jsonString格式,所以取出来key是String value也是String

  25. Map<String,String> map = jedis.hgetAll(jCacheKey);

  26. if(null !=map){

  27. for(Map.Entry<String, String> entry : map.entrySet()){

  28. if(result ==null){

  29. result =new HashMap<String,V>();

  30. }

  31. JSONObject obj = new JSONObject().fromObject(entry.getValue());//将json字符串转换为json对象

  32. v = (V)JSONObject.toBean(obj,object.getClass());//将建json对象转换为java对象

  33. result.put(entry.getKey(), v);

  34. }

  35. }

  36. } catch (JedisException e) {

  37. log.info("client can't connect server");

  38. if(null !=jedis){

  39. //释放jedis 对象

  40. redisUtil.brokenResource(jedis);

  41. }

  42. }

  43. return result;

  44. }

5.最后我们来测试一下,注意实际开发中肯定是再service层调用redis的操作接口,我这里写个简单的单元测试

第二种:序列化后存入redis, 我这里用SerializeUtil,不过我推荐使用ProtoBuff更好

  1. /**

  2. * Created by ${HeJD} on 2018/6/29.

  3. */

  4. @RunWith(SpringJUnit4ClassRunner.class)

  5. @ContextConfiguration(locations = {"classpath:applicationContext.xml"})

  6. public class RedisCacheStorageTest {

  7. @Autowired

  8. private RedisCacheStorage<String,User> redisCacheStorage;

  9. @Test

  10. public void testSetGet() throws Exception {

  11. System.out.print("开始执行测试");

  12. User user=new User();

  13. user.setUsername("admin7");

  14. user.setPassword("admin8");

  15. redisCacheStorage.set("Akey7",user);

  16. User user2= redisCacheStorage.get("Akey7",new User());

  17. System.out.print("======="+user2.getUsername()+"====="+user2.getPassword());

  18. }

代码在上一种方式的基础之上,我这里只写一些新的文件和需要修改的地方

1.首先我们需要一个序列化类

public class SerializeUtil {

/*

* 序列化

* */

public static byte[] serizlize(Object object){

ObjectOutputStream oos = null;

ByteArrayOutputStream baos = null;

3.最后测试的代码是一样的

(注意两个地方:1.这里是多实现,要用Qualifier指定注入的bean 2.序列化的方式实体类要实现Serializable接口)

2.我们需要对redis操作接口的实现类修改为另一种方式,我这里新建一个RedisCacheStorageImpl2来做对比

  1. @RunWith(S

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值