依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.1</version>
</dependency>
使用jedis
//创建jedis对象
Jedis jedis = new Jedis("192.168.8.10",6379);
//进行身份认证
jedis.auth("123456");
//判断是否连接成功
System.out.println(jedis.ping());
//通过jedis存储值和获取值
jedis.set("username","zzr");
System.out.println(jedis.get("username")); jedis.close();
使用jedisPool连接池
//创建jedisPool配置对象
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxWaitMillis(3000); //最大等待时间
config.setMaxTotal(1000); //最大连接数
config.setMaxIdle(500); //最大空闲连接数
//创建jedisPool连接池对象
JedisPool jedisPool = new JedisPool(config,"192.168.8.100",6379);
//获取jedis实例
Jedis jedis = jedisPool.getResource();
jedis.auth("123456");
//使用jedis存储值和获取值
jedis.set("age","18");
System.out.println(jedis.get("age"));
//关闭jedis(将jedis实例放回jedisPool)
jedis.close();
将jedisPool封装使用
- properties文件配置
redis.host=192.168.8.100:6379
redis.password=123456
redis.maxWaitMillis=3000
redis.maxTotal=1000
redis.maxIdle=500
- 封装到jedisBase类
public class jedisBase {
private JedisPoolConfig config;
private JedisPool jedisPool;
/**
* 获得JedisPool连接池
* @return
*/
public JedisPool getJedisPool() throws IOException {
//获取配置文件中的数据
Properties properties = new Properties();
properties.load(new FileInputStream("src/main/resources/application.properties"));
String redisHosts = properties.getProperty("redis.host");
String pwd = properties.getProperty("redis.password");
String maxWaitMillis = properties.getProperty("redis.maxWaitMillis");
String maxTotal = properties.getProperty("redis.maxTotal");
String maxIdle = properties.getProperty("redis.maxIdle");
//创建jedisPoolConfig对象,用于配置Redis连接池的参数
config = new JedisPoolConfig();
config.setMaxWaitMillis(Integer.parseInt(maxWaitMillis));
config.setMaxTotal(Integer.parseInt(maxTotal));
config.setMaxIdle(Integer.parseInt(maxIdle));
//创建jedisPool连接池
createJedisPool(redisHosts, pwd);
return jedisPool;
}
/**
* 创建jedisPool连接池
* @param redisHosts
* @param pwd
*/
private JedisPool createJedisPool(String redisHosts, String pwd) {
//获取主机和端口号
String host = redisHosts.split(":")[0].trim();
int port = Integer.parseInt(redisHosts.split(":")[1].trim());
if (pwd == null){
System.out.println("没有密码连接");
jedisPool = new JedisPool(config, host, port);
System.out.println("连接成功!");
}else {
System.out.println("有密码连接");
jedisPool = new JedisPool(config, host, port, 1000, pwd);
//测试连接
Jedis jedis = jedisPool.getResource();
System.out.println(jedis.ping());
System.out.println("连接成功!");
}
return jedisPool;
}
}
- 创建测试类进行测试
public class Test {
public static void main(String[] args) throws IOException {
jedisBase jedisBase = new jedisBase();
jedisBase.getJedisPool();
}
}