redis基础操作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了redis基础操作相关的知识,希望对你有一定的参考价值。
/**
* redis的Java客户端Jedis测试验证
*
* @author
*/
public class Test {
/**
* 非切片客户端链接
*/
private Jedis jedis;
/**
* 非切片链接池
*/
private JedisPool jedisPool;
/**
* 切片客户端链接
*/
private ShardedJedis shardedJedis;
/**
* 切片链接池
*/
private ShardedJedisPool shardedJedisPool;
private String ip = "172.16.205.186";
/**
* 构造函数
*/
public Test() {
initialPool();
initialShardedPool();
shardedJedis = shardedJedisPool.getResource();
jedis = jedisPool.getResource();
}
private void initialPool() {
// 池基本配置
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxActive(20);
config.setMaxIdle(5);
config.setMaxWait(1000l);
config.setTestOnBorrow(false);
jedisPool = new JedisPool(config, ip, 6379);
}
/**
* 初始化切片池
*/
private void initialShardedPool() {
// 池基本配置
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxActive(20);
config.setMaxIdle(5);
config.setMaxWait(1000l);
config.setTestOnBorrow(false);
// slave链接
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(ip, 6379, "master"));
// 构造池
shardedJedisPool = new ShardedJedisPool(config, shards);
}
public void show() {
// key检测
testKey();
// string检测
testString();
// list检测
testList();
// set检测
testSet();
// sortedSet检测
testSortedSet();
// hash检测
testHash();
shardedJedisPool.returnResource(shardedJedis);
}
private void testKey() {
System.out.println("=============key==========================");
// 清空数据
System.out.println(jedis.flushDB());
System.out.println(jedis.echo("foo"));
// 判断key否存在
System.out.println(shardedJedis.exists("foo"));
shardedJedis.set("key", "values");
System.out.println(shardedJedis.exists("key"));
}
private void testString() {
System.out.println("=============String==========================");
// 清空数据
System.out.println(jedis.flushDB());
// 存储数据
shardedJedis.set("foo", "bar");
System.out.println(shardedJedis.get("foo"));
// 若key不存在,则存储
shardedJedis.setnx("foo", "foo not exits");
System.out.println(shardedJedis.get("foo"));
// 覆盖数据
shardedJedis.set("foo", "foo update");
System.out.println(shardedJedis.get("foo"));
// 追加数据
shardedJedis.append("foo", " hello, world");
System.out.println(shardedJedis.get("foo"));