Jedis用于java语言连接redis服务,并提供对应的操作API
一、准备工作
(1)jar包导入
下载地址:https://mvnrepository.com/artifact/redis.clients/jedis
基于maven
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
(2)客户端连接redis
连接redis
Jedis jedis = new Jedis("localhost", 6379);
操作redis
jedis.set("name", "itheima"); jedis.get("name");
关闭redis连接
jedis.close();
二、代码实现
public class JedisTest {public static void main(String[] args) {//1.获取连接对象Jedis jedis = new Jedis("192.168.40.130",6379);//2.执行操作jedis.set("age","39");String hello = jedis.get("hello");System.out.println(hello);jedis.lpush("list1","a","b","c","d");List<String> list1 = jedis.lrange("list1", 0, -1);for (String s:list1 ) {System.out.println(s);}jedis.sadd("set1","abc","abc","def","poi","cba");Long len = jedis.scard("set1");System.out.println(len);//3.关闭连接jedis.close();}
}
三、Jedis简易工具类开发
3.1 基于连接池获取连接
- JedisPool:Jedis提供的连接池技术
- poolConfig:连接池配置对象
- host:redis服务地址
- port:redis服务端口号
JedisPool的构造器如下:
public JedisPool(GenericObjectPoolConfig poolConfig, String host, int port) {
this(poolConfig, host, port, 2000, (String)null, 0, (String)null);
}
3.2 封装连接参数
创建jedis的配置文件:jedis.properties
jedis.host=192.168.40.130
jedis.port=6379
jedis.maxTotal=50
jedis.maxIdle=10
3.3 加载配置信息
public class JedisUtils {private static int maxTotal;private static int maxIdel;private static String host;private static int port;private static JedisPoolConfig jpc;private static JedisPool jp;static {ResourceBundle bundle = ResourceBundle.getBundle("redis");maxTotal = Integer.parseInt(bundle.getString("redis.maxTotal"));maxIdel = Integer.parseInt(bundle.getString("redis.maxIdel"));host = bundle.getString("redis.host");port = Integer.parseInt(bundle.getString("redis.port"));//Jedis连接池配置jpc = new JedisPoolConfig();jpc.setMaxTotal(maxTotal);jpc.setMaxIdle(maxIdel);jp = new JedisPool(jpc,host,port);}}
3.4 获取连接
对外访问接口,提供jedis连接对象,连接从连接池获取,在JedisUtils中添加一个获取jedis的方法:getJedis
public static Jedis getJedis(){Jedis jedis = jedisPool.getResource();return jedis;
}
最后这里推荐redis可视化客户端
Redis Desktop Manager