<dependencies> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.6</version> </dependency> </dependencies>
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.3.2.RELEASE</version> <scope>import</scope> <type>pom</type> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
package com.jt; import org.junit.Test; import redis.clients.jedis.Jedis; public class JedisTests { @Test public void testGetConnection(){ //假如不能连通,要注释掉redis.conf中 bind 127.0.0.1, //并将protected-mode的值修改为no,然后重启redis再试 Jedis jedis=new Jedis("192.168.126.129",6379); //jedis.auth("123456");//假如在redis.conf中设置了密码 String ping = jedis.ping(); System.out.println(ping); } }
测试结果
注意保持一致:
@Test public void testString01(){ //1.创建连接对象 Jedis jedis=new Jedis(ip,port); //2.执行redis读写操作 //2.1想redis中存储字符串数据 jedis.set("id", "100"); jedis.expire("id", 2); jedis.set("token", UUID.randomUUID().toString()); jedis.incr("id"); Map<String,Object> map=new HashMap<>(); map.put("code", "201"); map.put("name", "redis"); Gson gson=new Gson(); String jsonStr = gson.toJson(map);//将map对象转换为json字符串 jedis.set("lession",jsonStr); //2.2删除数据 jedis.del("id"); //2.3获取数据 String id=jedis.get("id"); jsonStr=jedis.get("lession"); System.out.println(id); System.out.println(jsonStr); //3.释放资源 jedis.close(); }