新聞中心
Redis作為一款開源的內(nèi)存數(shù)據(jù)庫(kù),實(shí)現(xiàn)了豐富的數(shù)據(jù)類型與特性,支持靈活的持久性存儲(chǔ)方案,支持簡(jiǎn)單的Json格式存儲(chǔ),但是僅限實(shí)體類。在實(shí)際應(yīng)用中,為了更好地存儲(chǔ)持久化對(duì)象和對(duì)象實(shí)例,我們需要對(duì)對(duì)象進(jìn)行序列化,以便存儲(chǔ)其數(shù)據(jù)。

成都創(chuàng)新互聯(lián)是專業(yè)的科爾沁左翼網(wǎng)站建設(shè)公司,科爾沁左翼接單;提供成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè),網(wǎng)頁(yè)設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行科爾沁左翼網(wǎng)站開發(fā)網(wǎng)頁(yè)制作和功能擴(kuò)展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來合作!
Redis序列化存儲(chǔ)可以使用接口以及序列化框架,如Google的ProtoBuf或Kryo。實(shí)現(xiàn)序列化的前提是,需要在序列化對(duì)象上添加序列號(hào),并通過反射調(diào)用setter和getter方法來讀寫序列號(hào),而開發(fā)者可以選擇使用默認(rèn)的Java實(shí)現(xiàn)序列號(hào)操作的getter和setter方法,也可以自定義序列號(hào)的操作,以實(shí)現(xiàn)更豐富的數(shù)據(jù)存儲(chǔ)。
當(dāng)我們將序列化對(duì)象插入Redis后,系統(tǒng)會(huì)根據(jù)序列化結(jié)果自動(dòng)添加序列號(hào),所以在從Redis刪除對(duì)象時(shí),該對(duì)象也會(huì)被自動(dòng)序列化,減少了開發(fā)者手動(dòng)添加序列號(hào)的工作量。
下面給出所要實(shí)現(xiàn)的代碼,可用于Redis存儲(chǔ)序列化對(duì)象:
// 引入相關(guān)的jar包
org.redisson
redisson-all
3.5.3
// 創(chuàng)建redissonClient實(shí)例,其中compressionFormat表示序列化壓縮格式
public static RedissonClient getRedissonClient(SerializationCodec compressionFormat) {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379")
.setConnectionPoolSize(10)
.setConnectionMinimumIdleSize(10)
.setCodec(new SerializationCodec(compressionFormat));
return Redisson.create(config);
}
// 將對(duì)象插入Redis
public static void insert(RedissonClient redissonClient, Object object) {
try {
RBucket bucket = redissonClient.getBucket(object.getClass().getSimpleName());
bucket.set(object);
} catch (Exception e) {
e.printStackTrace();
} finally {
redissonClient.shutdown();
}
}
// 從Redis讀取對(duì)象
public static Object fetch(RedissonClient redissonClient, Class clazz) {
try {
RBucket bucket = redissonClient.getBucket(clazz.getSimpleName());
return bucket.get();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
redissonClient.shutdown();
}
}
通過上面的步驟,我們就可以利用Redis實(shí)現(xiàn)對(duì)象的序列化存儲(chǔ),盡快實(shí)現(xiàn)持久層的業(yè)務(wù)場(chǎng)景,而不需要在程序中自行實(shí)現(xiàn)序列化操作。
創(chuàng)新互聯(lián)(cdcxhl.com)提供穩(wěn)定的云服務(wù)器,香港云服務(wù)器,BGP云服務(wù)器,雙線云服務(wù)器,高防云服務(wù)器,成都云服務(wù)器,服務(wù)器托管。精選鉅惠,歡迎咨詢:028-86922220。
分享文章:Redis實(shí)現(xiàn)數(shù)據(jù)的序列化存儲(chǔ)(序列化后寫入redis)
轉(zhuǎn)載源于:http://m.fisionsoft.com.cn/article/cdhgsjs.html


咨詢
建站咨詢
