前言
借助Jedis可以在Java上操作Redis。
Jedis
到https://mvnrepository.com/去找jar包下载即可。
如果是maven项目:
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
获取连接
Jedis jedis = new Jedis('localhost');
jedis.auth(password); // 如果设置了密码,就需要先执行AUTH命令,否则执行其他操作会报错
连接池
JedisPoo 类是Jedis的连接池,可以用 GenericObjectPoolConfig 类来设置连接池,这里我用了Spring。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import javax.annotation.PostConstruct;
/**
* Created by fjh on 2017/6/15.
*/
@Component
public class JedisUtils {
private static JedisPool POOL;
private static volatile boolean flag = false;
@Value("${jedis.url:localhost}")
private String url;
@Value("${jedis.port:6379}")
private int port;
@Value("${jedis.timeout:1000}")
private int timeOut;
@Value("${jedis.auth}")
private String auth;
@Value("${jedis.pool.maxIdle:10}")
private int maxIdle;
@Value("${jedis.pool.maxTotal:100}")
private int maxTotal;
@Value("${jedis.pool.maxWaitMillis:10000}")
private long maxWaitMillis;
public static Jedis getResource() {
return POOL.getResource();
}
//带有`@PostConstruct`注解的方法会在属性注入之后执行
@PostConstruct
private void init() {
if (!flag) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(maxIdle);
config.setMaxTotal(maxTotal);
config.setMaxWaitMillis(maxWaitMillis);
POOL = new JedisPool(config, url, port, timeOut, auth);
flag = true;
}
}
}
调用代码:
Jedis jedis = null;
try {
jedis = JedisUtils.getResource();
System.out.println(jedis.keys("*"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null)
jedis.close();
}