pom依赖
<dependencies> <!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> </dependencies>
连接池管理类
package org.maple.redis; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * @author mapleins * @Date 2018-12-24 16:58 * @Desc 连接池管理 **/ public class RedisManager { private static JedisPool jedisPool; static { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); //设置连接参数,有很多方法 jedisPoolConfig.setMaxTotal(10); jedisPoolConfig.setMaxIdle(10); jedisPool = new JedisPool(jedisPoolConfig,"192.168.0.110",6379); } public static Jedis getJedis() throws Exception { if(null!=jedisPool){ Jedis jedis = jedisPool.getResource(); jedis.auth("123456"); return jedis; }else { throw new Exception("is not init"); } } }
基本操作和之前redis命令差不多,就不过多演示了
package org.maple.string; import org.junit.Test; import org.maple.redis.RedisManager; import redis.clients.jedis.Jedis; /** * @author mapleins * @Date 2018-12-24 17:06 * @Desc string测试 **/ public class StringTest { private Jedis jedis = RedisManager.getJedis(); public StringTest() throws Exception { } @Test public void test1() throws Exception { //1.设置指定的key value jedis.set("name", "jack"); //2.获取指定的key的value String name = jedis.get("name"); System.out.println("获取的值为:" + name); //3.获取截取的字符串 String trim = jedis.getrange("name", 0, 0); System.out.println("截取的值为:" + trim); //4.设置指定的key,value 返回旧的value,如果没有旧value,返回(nil),并设置key value String oldName = jedis.set("name", "rose"); System.out.println("旧的name:" + oldName); System.out.println("新的name:" + jedis.get("name")); } }