詳解在Java程序中運用Redis緩存對象的方法
這段時間一直有人問如何在Redis中緩存Java中的List 集合數(shù)據(jù),其實很簡單,常用的方式有兩種:
1. 利用序列化,把對象序列化成二進制格式,Redis 提供了 相關(guān)API方法存儲二進制,取數(shù)據(jù)時再反序列化回來,轉(zhuǎn)換成對象。
2. 利用 Json與java對象之間可以相互轉(zhuǎn)換的方式進行存值和取值。
正面針對這兩種方法,特意寫了一個工具類,來實現(xiàn)數(shù)據(jù)的存取功能。
1. 首頁在Spring框架中配置 JedisPool 連接池對象,此對象可以創(chuàng)建 Redis的連接 Jedis對象。當然,必須導(dǎo)入Redis的相關(guān)Jar包。
Jedis 的Jar包如下:
commons-pool2-2.3.jar
jedis-2.9.0.jar
要用到 Json,所以還需要導(dǎo)入Json的Jar包:
commons-beanutils-1.8.0.jar
commons-collections-3.1.jar
commons-lang-2.5.jar
commons-logging-1.1.3.jar
ezmorph-1.0.6.jar
json-lib-2.3-jdk15.jar
在配置文件中配置JedisPool 連接池對象
<!-- Redis 連接池配置 --> <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="close"> <constructor-arg name="host" value="127.0.0.1" /> <constructor-arg name="port" value="6379" /> </bean>
2. 創(chuàng)建一個Redis的工具類RedisUtil,這個類中實現(xiàn)了上面所說的兩種方法的存取操作
package com.sgxy.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import net.sf.json.JSONArray;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@Component
public class RedisUtil {
@Autowired
JedisPool pool; // Jedis連接池
// 判斷Redis中是否存在鍵
public boolean existsKey(String key) {
Jedis jedis = pool.getResource();
boolean bool;
try {
bool = jedis.exists(key);
} finally {
jedis.close();
}
return bool;
}
// 取緩存中的二進制數(shù)據(jù),反序列化成List集合對象
@SuppressWarnings("unchecked")
public <T> List<T> getObject(String key, Class<T> clazz) {
Jedis jedis = pool.getResource();
// 二進制 IO 輸入流
ByteArrayInputStream is = null;
ObjectInputStream ois = null;
try {
// 從緩存中取二進制數(shù)據(jù)
byte[] b = jedis.get(key.getBytes());
is = new ByteArrayInputStream(b);
ois = new ObjectInputStream(is);
// 把二進制轉(zhuǎn)換成T指定類型的集合
return (List<T>) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
ois.close();
} catch (Exception e2) {
e2.printStackTrace();
}
jedis.close();
}
return null;
}
// 把對象序列化二進制格式并保證到Redis緩存中
public void saveObject(Object object, String key) {
Jedis jedis = pool.getResource();
// 二進制 IO 輸出流
ByteArrayOutputStream os = null;
ObjectOutputStream oos = null;
try {
os = new ByteArrayOutputStream();
oos = new ObjectOutputStream(os);
oos.writeObject(object); // 二進制數(shù)據(jù)
byte[] b = os.toByteArray();
// 存入二進制數(shù)據(jù)到Redis緩存中
jedis.set(key.getBytes(), b);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
oos.close();
} catch (Exception e2) {
e2.printStackTrace();
}
jedis.close();
}
}
// 把List集合對象轉(zhuǎn)換成json格式保存到指定的鍵中
public void saveJsonArray(Object object, String key) {
Jedis jedis = pool.getResource();
try {
// 格式化成Json字符串
JSONArray array = JSONArray.fromObject(object);
jedis.set(key, array.toString()); // 存入緩存
} finally {
jedis.close();
}
}
// 通過鍵取出Json字符串并轉(zhuǎn)換成 Class<T>這個T所指定的類型
@SuppressWarnings({ "static-access", "unchecked" })
public <T> List<T> getJsonArray(String key, Class<T> clazz) {
Jedis jedis = pool.getResource();
try {
String str = jedis.get(key);
JSONArray array = JSONArray.fromObject(str);
// 把字符串轉(zhuǎn)換回集合對象 clazz是指定的類型
return (List<T>) array.toCollection(array, clazz);
} finally {
jedis.close();
}
}
}
在Java程序其他地方操作這個工具類做數(shù)據(jù)的處理:
@Controller //注解這個類為控制器
@RequestMapping("grade") //注冊訪問此控制器的URL
public class GradeController {
@Autowired // 從IOC容器注入業(yè)務(wù)層對象
GradeService gradeService;
@Autowired
JedisPool pool;
@Autowired
RedisUtil redisUtil;
@RequestMapping("list") //注冊URL
public ModelAndView list() {
List<Grade> grades = null;
if (redisUtil.existsKey("g")) {
System.out.println("從Redis 緩存中取數(shù)據(jù)..");
//調(diào)用反序列化方法取緩存的數(shù)據(jù)
grades = redisUtil.getObject("g",Grade.class);
//調(diào)用Json格式轉(zhuǎn)換的方法取緩存數(shù)據(jù)
//grades = redisUtil.getJsonArray("gradeList", Grade.class);
} else {
System.out.println("從數(shù)據(jù)庫中取數(shù)據(jù),并存入緩存..");
//調(diào)用底層方法從數(shù)據(jù)庫中取數(shù)據(jù)
grades = gradeService.find();
//調(diào)用序列化方法把數(shù)據(jù)緩存到Redis中
redisUtil.saveObject(grades, "g");
//調(diào)用Json格式化方法把數(shù)據(jù)緩存到Redis中
//redisUtil.saveJsonArray(grades, "gradeList");
}
return new ModelAndView("gradeList", "grades", grades);
}
}
寫到此,希望對大家有所幫助。
以上所述是小編給大家介紹的在Java程序中運用Redis緩存對象的方法詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Java利用happen-before規(guī)則如何實現(xiàn)共享變量的同步操作詳解
這篇文章主要給大家介紹了關(guān)于Java利用happen-before規(guī)則實現(xiàn)共享變量的同步操作的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用java具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-06-06
Spring Batch讀取txt文件并寫入數(shù)據(jù)庫的方法教程
這篇文章主要給大家介紹了Spring Batch讀取txt文件并寫入數(shù)據(jù)庫的方法,SpringBatch 是一個輕量級、全面的批處理框架。這里我們用它來實現(xiàn)文件的讀取并將讀取的結(jié)果作處理,處理之后再寫入數(shù)據(jù)庫中的功能。需要的朋友可以參考借鑒,下面來一起看看吧。2017-04-04
Java?CompletableFuture實現(xiàn)原理分析詳解
CompletableFuture是Java8并發(fā)新特性,本文我們主要來聊一聊CompletableFuture的回調(diào)功能以及異步工作原理是如何實現(xiàn)的,需要的可以了解一下2022-09-09
elasticsearch索引的創(chuàng)建過程index?create邏輯分析
這篇文章主要介紹了elasticsearch索引核心index?create,索引的創(chuàng)建過程解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04

