jedis使用
1.创建maven项目,引入jar包
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
2.进行连接测试
创建一个测试连接的类:
public class JedisDemo1 {
public static void main(String[] args) {
//创建jedis对象
Jedis jedis = new Jedis("host",port);
//设置密码了 需要加上这个进行认证
jedis.auth("........");
String ping = jedis.ping();
System.out.println(ping);
}
}
输出结果为:PONG
3.进行对各种数据类型进行操作
3.1操作string
//操作string
public void demo1(){
Jedis jedis = new Jedis("host",6380);
//设置密码了 需要加上这个进行认证
jedis.auth("密码");
jedis.set("name","jerry");
String name = jedis.get("name");
System.out.println(name);
// Set<String> keys = jedis.keys("*");
// for (String key : keys) {
// System.out.println(key);
// }
}
3.2 操作list
@Test
public void demo2(){
Jedis jedis = new Jedis("host",6380);
//设置密码了 需要加上这个进行认证
jedis.auth();
jedis.lpush("list1","java");
jedis.lpush("list1","c++");
jedis.rpush("list1","c#");
List<String> list1 = jedis.lrange("list1", 0, -1);
for (String s : list1) {
System.out.println(s);
}
}
3.3操作set
/**
* 操作set
*/
@Test
public void demo3(){
jedis.sadd("set1","java");
jedis.sadd("set1","name");
jedis.sadd("set1","c++");
Set<String> smembers = jedis.smembers("set1");
for (String smember : smembers) {
System.out.println(smember);
}
}
3.4操作hash
/**
* 操作hash数据
*/
@Test
public void demo4(){
HashMap<String, String> stringStringHashMap = new HashMap<>();
stringStringHashMap.put("name","zhangsan");
stringStringHashMap.put("age","22");
jedis.hset("user",stringStringHashMap);
String hget = jedis.hget("user", "name");
System.out.println(hget);
}
//输出 zhangsan
3.5操作zset
@Test
public void demo5(){
jedis.zadd("yuyan",300,"java");
jedis.zadd("yuyan",100,"c++");
jedis.zadd("yuyan",10,"c#");
jedis.zadd("yuyan",1,"php");
Set<String> yuyan = jedis.zrange("yuyan", 0l, -1l);
for (String s : yuyan) {
System.out.println(s);
}
}
标签:String,System,jedis,使用,println,方法,public,name
From: https://www.cnblogs.com/wiseleer/p/16906582.html