jedis
Jedis是Redis官方推荐的Java链接工具
使用前导入,下面的测试建议也导入测试的包
<!-- jidisd的包-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- test的包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
创建测试类
import com.util.JedisUtils;
import org.junit.Test;
import redis.clients.jedis.Jedis;
public class JedisTest {
@Test
public void testJedis(){
//1.链接redis
Jedis jedis = new Jedis(“127.0.0.1”,6379); //直接链接
//Jedis jedis= JedisUtils.getJedis(); //使用连接池
//2.操作redis
jedis.set(“name”,“aa”);
System.out.println(jedis.get(“name”));
//3.关闭redis
jedis.close();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
以上是没有连接池的
当然我们也可以使用连接池
完成redis.properties
redis.host=127.0.0.1
redis.port=6379
redis.maxTotal=30
redis.maxIdle=10
- 1
- 2
- 3
- 4
package com.util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.ResourceBundle;
/**
- 手写连接池
*/
public class JedisUtils {
private static JedisPool jp;
private static String host;
private static int port;
private static int maxTotal;
private static int maxIdle;
static {
JedisPoolConfig jpc=new JedisPoolConfig();
ResourceBundle rb=ResourceBundle.getBundle(“redis”);
host=rb.getString(“redis.host”);
port=Integer.parseInt(rb.getString(“redis.port”));
maxTotal=Integer.parseInt(rb.getString(“redis.maxTotal”));
maxIdle=Integer.parseInt(rb.getString(“redis.maxIdle”));
jpc.setMaxTotal(maxTotal);
jpc.setMaxIdle(maxIdle);
jp=new JedisPool(jpc,host,port);
}
public static Jedis getJedis(){
return jp.getResource();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
不论是采用连接池或者是手动链接测试结果如下