手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Spring集成Redis实例入门

[日期:2013-04-25] 来源:Linux社区  作者:shaopeng5211 [字体:大 中 小]

测试类:

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;
 }
}

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款