测试类:
package com.duobei.Redis;
import Java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.duobei.memcached.model.User;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
public class RedisTest {
private ApplicationContext context;
private ShardedJedisPool shardedJedisPool;
private ShardedJedis jedis;
public RedisTest() {
}
@Before
public void init() throws Exception {
String config[] = { "applicationContext.xml",
"applicationContext-redis.xml" };
context = new ClassPathXmlApplicationContext(config);
shardedJedisPool = (ShardedJedisPool) context
.getBean("shardedJedisPool");
jedis = (ShardedJedis) shardedJedisPool.getResource();
}
@Test
@Ignore
public void testSet() {
System.out.println(jedis.set("name", "changxiaoxiao"));
}
@Test
@Ignore
public void testGet() {
System.out.println(jedis.get("name"));
}
@Test
@Ignore
public void addOne() {
/*
* 构造一个User对象
*/
User user = new User();
user.setName("changxiaoxiao");
user.setPass("changxiaoxiao");
jedis.set("userOne".getBytes(), ObjectToByte(user));
System.out.println("添加成功!");
}
@Test
//@Ignore
public void show() {
byte[] bytes = jedis.get("userOne".getBytes());
User user = (User) ByteToObject(bytes);
System.out.println("Name:" + user.getName());
System.out.println("Password:" + user.getPass());
}
/**
* 对象序列化
* @param obj
* @return
*/
public byte[] ObjectToByte(Object obj) {
byte[] bytes = null;
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
bytes = bo.toByteArray();
bo.close();
oo.close();
}
catch(Exception e) {
e.printStackTrace();
}
return bytes;
}
/**
* 反序列化
* @param bytes
* @return
*/
public Object ByteToObject(byte[] bytes) {
Object object = null;
try {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
object = ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
}
