在java中如何操作redis呢
使用jedis,Jedis 是 Redis 官方首选的 Java 客户端开发包\
使用jedis
下载
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.5.1</version>
</dependency>
hello world
final static String URL = "localhost";
final static int PORT = 6379;
@Test
public void test_String() {
// 1.连接jedis
Jedis jedis = new Jedis(URL, PORT);
// 2.存取数据
jedis.set("name", "itheima");
String name = jedis.get("name");
System.out.println(name);
// 3.关闭资源
jedis.close();
}
jedis pool
jedis为我们提供了jedispool(连接池)对象
我们可以从连接池中获取jedis对象
public class RedisFactory {
/**
* redis config文件的名称 默认从classpath下加载
*/
final static String CONFIG_NAME = "redis_config.properties";
private static RedisFactory factory;
private JedisPool pool;
private RedisFactory() {
factory = this;
try {
// 从属性文件中加载数据
InputStream in = RedisFactory.class.getClassLoader().getResourceAsStream(CONFIG_NAME);
Properties reader = new Properties();
reader.load(in);
// 指定连接的端口号
Integer port = Integer.parseInt(reader.getProperty("redis.connect.port"));
// 指定连接的地址
String address = reader.getProperty("redis.connect.address");
// 链接池中最大连接数
Integer maxActive = Integer.parseInt(reader.getProperty("redis.connect.maxActive"));
// 链接池中最大空闲的连接数
Integer maxIdle = Integer.parseInt(reader.getProperty("redis.connect.maxIdle"));
// 链接池中最小空闲的连接数
Integer minIdle = Integer.parseInt(reader.getProperty("redis.connect.minIdle"));
// pool详细配置都可以通过JedisPoolConfig来实现
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxActive);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
this.pool = new JedisPool(config, address, port);
} catch (IOException e) {
e.printStackTrace();
}
}
public static RedisFactory newInstance() {
return factory == null ? new RedisFactory() : factory;
}
/**
* 通过jedis pool获取jedis实例对象
*
* @return
*/
public Jedis getResource() {
return this.pool.getResource();
}
}
配置文件redis_config.properties
# redis server连接参数
## 连接的端口号
redis.connect.port=6379
## 连接的地址
redis.connect.address=localhost:
## 链接池中最大连接数
redis.connect.maxActive=20
## 链接池中最大空闲的连接数
redis.connect.maxIdle=20
## 链接池中最少空闲的连接数
redis.connect.minIdle=20