上一篇博客中介绍了redis的基本数据,这篇博客就简单介绍通过客户端操作redis。
1、新建一个简单的项目,在pom.xml中引入如下依赖
<dependencies>
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
<version>2.9.0version>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
<version>3.4version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
dependency>
<dependency>
<groupId>com.google.guavagroupId>
<artifactId>guavaartifactId>
<version>21.0version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.16.20version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.5version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-simpleartifactId>
<version>1.7.25version>
dependency>
dependencies>
2、编写一个简单的测试类
@Slf4j
public class SimpleTest {
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.72.128", 6379);
jedis.set("liman", "2673");
log.info("jedis simple get result:{}",jedis.get("liman"));
jedis.close();
}
}
3、运行结果
这里以zset和hash为例进行说明
/**
* autor:liman
* createtime:2020/7/4
* comment:ZSet的实例
*/
@Slf4j
public class ZSetTest {
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.72.128", 6379);
//zadd 往zset中增加元素
jedis.zadd("myzset", 20, "java");
jedis.zadd("myzset", 30, "python");
jedis.zadd("myzset", 90, "ruby");
jedis.zadd("myzset", 40, "erlang");
jedis.zadd("myzset", 70, "cpp");
jedis.zadd("myzset", 50, "android");
//按照分数倒序排列
Set<String> set = jedis.zrevrangeByScore("myzset", 100, 10);
log.info("redis zset content:{}",set);
}
}
运行结果
/**
* autor:liman
* createtime:2020/7/4
* comment:
*/
@Slf4j
public class HashTest {
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.72.128", 6379);
Map<String,String> hmap = new HashMap<>();
hmap.put("h1","a");
hmap.put("h2","b");
hmap.put("h3","c");
hmap.put("h4","d");
hmap.put("h5","e");
//存放map元素
jedis.hmset("hmap",hmap);
//获取map元素
List<String> mapValue = jedis.hmget("hmap", "h1", "h2", "h3", "h4", "h5");
log.info("hmapValue:{}",mapValue);
}
}
运行结果
本篇博客简单实用jedis连接redis进行了相关操作,比较简单,后面的redis博客总结会在这个基础上进行一些案例的操作。