java在redis中進行對象的緩存一般有兩種方法,這里介紹序列化的方法,個人感覺比較方便,不需要轉(zhuǎn)來轉(zhuǎn)去。
一、首先,在存儲的對象上實現(xiàn)序列化的接口
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( "緩存服務(wù)器連接異常!" ); 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( "緩存服務(wù)器連接異常!" ); e.printstacktrace(); } finally { // 返還到連接池 jedis.close(); } return serializeutil.unserialize(obj); } |
可以看到,redis中存儲的是序列化之后的對象
以上所述是小編給大家介紹的java在redis中進行對象的緩存詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://blog.csdn.net/qq_20989105/article/details/79173618