目录
一、基本使用
1、xml 引入依赖
2、简单测试
二、工具类
1、编写redis属性文件
2、编写工具类
3、使用测试
Jedis是Redis官方推荐的Java连接开发工具。
一、基本使用
1、xml 引入依赖
<dependencies><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId> <!--redis的java客户端--><version>3.4.0</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.70</version></dependency></dependencies>
2、简单测试
public class RedisTest {@Testpublic void testSet(){//通过指定host、port、password创建Jedis对象Jedis jedis = new Jedis("127.0.0.1",6379);jedis.auth("lly123");//set操作jedis.set("test","valueTest");//get操作String v = jedis.get("test");System.out.println(v);}
}
二、工具类
1、编写redis属性文件
redis.host=127.0.0.1
redis.port=6379
redis.password=lly123
#最大连接数
redis.maxTotal=20
#最大活跃数
redis.maxIdle=10
#最长等待时间
redis.maxWaitMillis=3000
2、编写工具类
package Util;import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;import java.io.IOException;
import java.util.Properties;public class RedisUtil {private JedisPool pool = null;//单例模式private static RedisUtil instance = new RedisUtil();//私有构造函数private RedisUtil() {if (pool == null) {//获取redis连接属性文件Properties properties = new Properties();try {properties.load(RedisUtil.class.getClassLoader().getResourceAsStream("redis.properties"));} catch (IOException e) {e.printStackTrace();}String ip = (String) properties.get("redis.host");int port = Integer.parseInt(properties.get("redis.port").toString()) ;String password = (String) properties.get("redis.password");JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();jedisPoolConfig.setMaxTotal(Integer.parseInt(properties.get("redis.maxTotal").toString()));jedisPoolConfig.setMaxIdle(Integer.parseInt(properties.get("redis.maxIdle").toString()));jedisPoolConfig.setMaxWaitMillis(Long.parseLong(properties.get("redis.maxWaitMillis").toString()));if (password != null && !"".equals(password)) {// redis 设置了密码pool = new JedisPool(jedisPoolConfig, ip, port, 10000, password);} else {// redis 未设置密码pool = new JedisPool(jedisPoolConfig, ip, port, 10000);}}}public Jedis getJedis() {return pool.getResource();}public static RedisUtil getInstance() {return instance;}}
3、使用测试
public class RedisTest {private RedisUtil redisUtil = RedisUtil.getInstance();@Testpublic void testPool(){//每次从池中获取jedis,而不是每次都去new一个Jedis jedis = redisUtil.getJedis();//存取测试jedis.set("pool_key","pool_value");String v = jedis.get("pool_key");System.out.println(v);//使用完记得关闭jedis.close();}
}