好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解Java在redis中进行对象的缓存

java在redis中进行对象的缓存一般有两种方法,这里介绍序列化的方法,个人感觉比较方便,不需要转来转去。

一、首先,在存储的对象上实现序列化的接口

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

package com.cy.example.entity.system;

 

import java.util.list;

 

import com.baomidou.mybatisplus.annotations.tablefield;

import com.baomidou.mybatisplus.annotations.tablename;

import com.cy.example.entity.superentity;

 

@tablename ( "users" )

public class sysuserentity extends superentity<sysuserentity> {

 

  /**

   * 序列化

   */

  private static final long serialversionuid = -2967710007706812401l;

 

  private string c_username;

 

  private string c_pwd;

 

  private string c_phone;

 

  private string c_email;

 

  private string n_age;

 

  private string n_sex;

 

  private string n_status;

 

  private sysdepartmententity n_departmentid;

 

  @tablefield (exist = false )

  private list<sysroleentity> rolelist; // 一个用户具有多个角色

 

  private sysuserentity n_superior;

 

  //省略getter、setter

}

二、进行存储的编写

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

// 存储对象

  public void setobject(string key, object obj) {

   jedis jedis = null ;

   try {

    jedis = pool.getresource();

    jedis.set(key.getbytes(), serializeutil.serialize(obj));

   } catch (exception e) {

    logger.info( "缓存服务器连接异常!" );

    e.printstacktrace();

   } finally {

    // 返还到连接池

    jedis.close();

   }

  }

三、获取存储的对象

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

// 获取对象

  public object getobject(string key) {

 

   byte [] obj = null ;

   jedis jedis = null ;

   try {

    jedis = pool.getresource();

    obj = jedis.get(key.getbytes());

   } catch (exception e) {

    logger.info( "缓存服务器连接异常!" );

    e.printstacktrace();

   } finally {

    // 返还到连接池

    jedis.close();

   }

   return serializeutil.unserialize(obj);

  }

可以看到,redis中存储的是序列化之后的对象

以上所述是小编给大家介绍的java在redis中进行对象的缓存详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

原文链接:https://blog.csdn.net/qq_20989105/article/details/79173618

查看更多关于详解Java在redis中进行对象的缓存的详细内容...

  阅读:28次