redis拾遗(二)——jedis连接redis

    技术2025-09-04  31

    前言

    上一篇博客中介绍了redis的基本数据,这篇博客就简单介绍通过客户端操作redis。

    简单连接实例

    1、新建一个简单的项目,在pom.xml中引入如下依赖

    <dependencies> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>21.0</version> </dependency> <!--jdk&lombok simple log start--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.25</version> </dependency> <!--jdk&lombok simple log end--> </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为例进行说明

    zset

    /** * 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); } }

    运行结果

    hash

    /** * 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博客总结会在这个基础上进行一些案例的操作。

    Processed: 0.012, SQL: 9