首先需要下载个Redis安装包,网上有。
首先我们需要对redis进行一些配置,可以建一个Util类
package com.redis.util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtil {
private static String ip="localhost";
private static int port=6379;
private static int timeout=10000;
private static JedisPool pool=null;
static{
JedisPoolConfig config=new JedisPoolConfig();
config.setMaxTotal(1024);//大连接数
config.setMaxIdle(200);//大空闲实例数
config.setMaxWaitMillis(10000);//等连接池给连接的大时间,毫秒
config.setTestOnBorrow(true);//个实例的时,是否提前vaildate操作
pool=new JedisPool(config,ip,port,timeout);
}
//得到redis连接
public static Jedis getJedis(){
if(pool!=null){
return pool.getResource();
}else{
return null;
}
}
//关闭redis连接
public static void close(final Jedis redis){
if(redis != null){
redis.close();
}
}
}
对于普通的字符存储是非常简单的,但是对于对象和list集合则牵扯的序列化的问题,我们可以创建几个用于序列化的工具类
/*
*对象序列化与反序列化
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeUtil {
/**
*
* 序列化
*/
public static byte[] serialize(Object obj) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
byte[] byteArray = baos.toByteArray();
return byteArray;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
*
* 反序列化
*
* @param bytes
* @return
*/
public static Object unSerialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
// 反序列化为对化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/*
* list集合序列化与反序列化
* */
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class SerializeUtilList {
/**
* 序列化 list 集合
*
* @param list
* @return
*/
public static byte[] serializeList(List<?> list) {
if (list == null || list.size() == 0) {
return null;
}
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
byte[] bytes = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
for (Object obj : list) {
oos.writeObject(obj);
}
bytes = baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(oos);
close(baos);
}
return bytes;
}
/**
* 反序列化 list 集合
*
* @param lb
* @return
*/
public static List<?> unserializeList(byte[] bytes) {
if (bytes == null) {
return null;
}
List<Object> list = new ArrayList<Object>();
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
while (bais.available() > 0) {
Object obj = (Object) ois.readObject();
if (obj == null) {
break;
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(bais);
close(ois);
}
return list;
}
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
这样大体的内容就完成了,当然存取list集合的过程相对而言有些繁琐,我们也可以封装起来建一个类,以便于测试的时候调用更方便
import java.util.List;
import redis.clients.jedis.Jedis;
import com.redis.util.RedisUtil;
import com.redis.util.SerializeUtilList;
public class MiddleList {
/*
* 存储list集合
* */
public static void setList(String key ,List<?> list){
Jedis jedis=RedisUtil.getJedis();
try {
if(list == null || list.size() == 0){
jedis.set(key.getBytes(), "".getBytes());
}else{//如果list为空,则设置一个空
jedis.set(key.getBytes(), SerializeUtilList.serializeList(list));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
}
/**
* 获取List集合
* @param key
* @return
*/
public static List<?> getList(String key){
Jedis jedis=RedisUtil.getJedis();
if(jedis == null || !jedis.exists(key)){
return null;
}
byte[] data = jedis.get(key.getBytes());
jedis.close();
return SerializeUtilList.unserializeList(data);
}
}
之后我们可以建一个实体类以便于测试
import java.io.Serializable;
public class User implements Serializable{
private Integer userid;
private String username;
private String password;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "user [userid=" + userid + ", username=" + username
+ ", password=" + password + "]";
}
public User(Integer userid, String username, String password) {
super();
this.userid = userid;
this.username = username;
this.password = password;
}
public User() {
super();
}
}
准备工作完成,现在可以进行测试了
public class RedisTest {
public static void main(String[] args) {
// 将一个对象序列化存储进redis缓存中,并将他取出来
Jedis redis=RedisUtil.getJedis();
redis.set("aaaaaaa","bbbbbbbbbbb");
redis.get("aaaaaaa");
User user=new User();
user.setUserid(1);
user.setUsername("tom");
user.setPassword("123456");
//存储对象
redis.set("user".getBytes(),SerializeUtil.serialize(user));
//从redis取出user后,把user对象反序列化
User user2=(User) SerializeUtil.unSerialize(redis.get("user".getBytes()));
//存储list集合
List<User> list=new ArrayList<User>();
User user1=new User();
user1.setUserid(2);
user1.setUsername("jack");
user1.setPassword("123456");
User user2=new User();
user2.setUserid(3);
user2.setUsername("larry");
user2.setPassword("123456");
list.add(user);
list.add(user1);
list.add(user2);
List<User> list=Middle.createUsers();
//存储缓存
MiddleList.setList("getlist", list);
//取缓存
List<User> lists = (List<User>) MiddleList.getList("getlist");
for(int i=0;i<lists.size();i++){
System.out.println(lists.get(i));
}
}
}