jedis简单使用
导入相关jar包
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.8.0</version>
</dependency>
jedis的简单操作
public class JedisTest {
private Jedis jedis;
@Before
public void init(){
jedis = new Jedis("192.168.0.130", 6379);
}
@Test
public void keysTest(){
Set<String> keys = jedis.keys("*");
for (String key : keys) {
System.out.println(key + "\t" + jedis.get(key));
}
System.out.println(jedis.exists("test"));
System.out.println(jedis.ttl("test"));
}
@Test
public void stringTest(){
jedis.append("k1","myreids");
System.out.println(jedis.get("k1"));
jedis.set("k4","k4_redis");
System.out.println("----------------------------------------");
jedis.mset("str1","v1","str2","v2","str3","v3");
System.out.println(jedis.mget("str1","str2","str3"));
}
@Test
public void listTest(){
Long mylist = jedis.lpush("mylist", "v1", "v2", "v3", "v4");
System.out.println(mylist);
List<String> list = jedis.lrange("mylist", 0L, -1L);
list.forEach(System.out::println);
}
@Test
public void setTest(){
jedis.sadd("myset", "001");
jedis.sadd("myset", "002");
jedis.sadd("myset", "003");
jedis.sadd("myset", "004");
Set<String> myset = jedis.smembers("myset");
myset.forEach(System.out::println);
System.out.println(myset.size());
jedis.srem("myset","002");
myset = jedis.smembers("myset");
myset.forEach(System.out::println);
System.out.println(myset.size());
}
@Test
public void hashTest(){
jedis.hset("hash1", "username", "lisi");
System.out.println(jedis.hget("hash1", "username"));
Map<String, String> map = new HashMap<>();
map.put("add", "beijing");
map.put("name", "zhangsan");
map.put("gender", "男");
Long aLong = jedis.hset("myhash", map);
System.out.println(aLong);
List<String> myhash = jedis.hvals("myhash");
myhash.forEach(System.out::println);
}
@Test
public void zsetTest(){
jedis.zadd("myzset",60d,"v1");
jedis.zadd("myzset",70d,"v2");
jedis.zadd("myzset",80d,"v3");
jedis.zadd("myzset",90d,"v4");
Set<String> myzset = jedis.zrange("myzset", 0, -1);
myzset.forEach(System.out::println);
}
}
redis中文显示
在启动redis-cli的时候加上 --raw 即可
[root@localhost src]# ./redis-cli -p 6379
127.0.0.1:6379> set name 张三
OK
127.0.0.1:6379> get name
"\xe5\xbc\xa0\xe4\xb8\x89"
127.0.0.1:6379> exit
[root@localhost src]# ./redis-cli -p 6379 --raw
127.0.0.1:6379> get name
张三
127.0.0.1:6379>