Redis - Jedis 操作 Redis
要导入的包
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
代码
public void redis(){ //1.生成一个jedis对象,这个对象负责和指定Redis节点进行通信 Jedis jedis = new Jedis("124.223.94.17", 6379); //带密码需要执行认证方法 jedis.auth("leviAckerman2641949252"); String ping = jedis.ping(); }
池
package com.didinx.filter; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * @author o_0sky * @date 2019/2/14 1:33 */ public class JedisPool1 { public static void main(String[] args) { //生成连接池配置对象,设置配置项 JedisPoolConfig config = new JedisPoolConfig(); //最大连接数 config.setMaxTotal(100); //最大空闲数 config.setMaxIdle(20); //获得连接池 JedisPool jedisPool = new JedisPool(config, "localhost", 6379); Jedis jedis = null; try { //从连接池获取连接 jedis = jedisPool.getResource(); //给连接赋值 jedis.set("age", "30"); //从连接池中取值并打印 System.out.println(jedis.get("age")); } catch (Exception e) { e.printStackTrace(); } finally { //此处jedis.close()并不是销毁连接,而是将连接返回连接池 if (null != jedis) { jedis.close(); } } //电脑关闭时,关闭连接池 if (null != jedisPool) { jedisPool.close(); } } }
工具类
package didinx; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.ResourceBundle; /** * @author o_0sky * @date 2019/2/14 1:49 */ public class JedisUtil { //设置参数 private static String host; private static int port; private static int maxtotal; private static int maxwaitmillis; private static JedisPool jedisPool; //加载配置文件并给参数赋值 static { ResourceBundle rb = ResourceBundle.getBundle("jedis"); maxtotal = Integer.parseInt(rb.getString("maxtotal")); maxwaitmillis = Integer.parseInt(rb.getString("maxwaitmillis")); port = Integer.parseInt(rb.getString("port")); host = rb.getString("host"); } /** * 初始化连接池 */ static { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(maxtotal); config.setMaxWaitMillis(maxwaitmillis); jedisPool = new JedisPool(config, host, port); } /** * 获取连接方法 * * @return */ public static Jedis getJedis() { return jedisPool.getResource(); } /** * 释放资源 * * @param jedis */ public static void closeJedis(Jedis jedis) { if (null != jedis) { jedis.close(); } } }