java中redis的使用

来源:互联网 发布:数据汇集平台 编辑:程序博客网 时间:2024/06/06 01:35
import java.util.HashSet;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;


public class JadisTest {


@Test
public void testJadisSing(){
//创建Jadis 对象
Jedis jedis = new Jedis("123.206.46.51", 6379);
//调用Jedis 方法,跟redis 指令一样
jedis.set("key1", "Jedis Test");
String result = jedis.get("key1");
System.out.println(result);
//关闭Jedis
jedis.close();
}
/**
        * JedisPool 
        */
@Test
public void testJedisPool(){
//创建Jedis 连接池对象
JedisPool pool = new JedisPool("123.206.46.51", 6379);
//从连接池中取Jedis对象
Jedis jedis = pool.getResource();
//调用Jedis 方法
String result = jedis.get("key1");
System.out.println(result);
//关闭Jedis
jedis.close();
//关闭连接池
pool.close();
}

/**
* redis 群集
*/
@Test
public void testJedisCluster(){

HashSet<HostAndPort> nodes = new HashSet<>();
nodes.add(new HostAndPort("123.206.46.51", 7001));
nodes.add(new HostAndPort("123.206.46.51", 7002));
nodes.add(new HostAndPort("123.206.46.51", 7003));
nodes.add(new HostAndPort("123.206.46.51", 7004));
nodes.add(new HostAndPort("123.206.46.51", 7005));
nodes.add(new HostAndPort("123.206.46.51", 7006));
JedisCluster cluster = new JedisCluster(nodes);

cluster.set("key1","100");
String str = cluster.get("key1");
System.out.println(str);
}

/**
* 基于spring 的单机版的 redis
*/
@Test
public void testJedisSpring(){
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
JedisPool jedisPool = (JedisPool) context.getBean("redisClient");
Jedis jedis = jedisPool.getResource();
System.out.println(jedis.get("key1"));

jedis.close();
jedisPool.close();
}

@Test
public void testJedisCluterSpring(){
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
JedisCluster cluster = (JedisCluster) context.getBean("redisClient");
System.out.println(cluster.get("key1"));
}


}
原创粉丝点击