java中redis的使用

9 篇文章 0 订阅

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值