jedis: Use Java call Redis
First, install jedis
Before you start using Redis in Java, we need to ensure that services and Java redis redis drive already installed on your machine and normal use Java. To install redis here it is not described in detail. I can refer to Bowen Linux installation redis next .
Download jedis driver package, I use the maven way to import, simply and quickly, we can from the Maven Repository download, select a higher version than download.
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
Thus, jedis driver package has been imported, the following java code started connected redis.
Second, the connection Redis
First, let's get to the IP and port number to start redis server, the default port 6379 is generally used. Use the code below to test whether redis can successfully connect.
@Test
public void connTest() {
Jedis jedis = new Jedis("192.168.0.106", 6379);
System.out.println("连接成功!");
System.out.println("服务正在运行: " + jedis.ping());
jedis.set("name", "jie_ming514");
String name = jedis.get("name");
System.out.println(name);
}
Console information:
Then we went to look at the name redis on this key is equal to "jie_ming514"
the OK, the information is completely correct, the connection is no problem.
Third, different types of data stored in a data structure Redis
3.1. String type
@Test
public void redisStringTest() {
Jedis jedis = new Jedis("192.168.0.106", 6379);
System.out.println("连接成功!");
jedis.set("name", "jie_ming514");
String name = jedis.get("name");
System.out.println(name);
System.out.println("redis 存储的字符串为: "+ jedis.get("name"));
}
Output:
3.2.list type
@Test
public void redisListTest() {
//连接本地的 Redis 服务
Jedis jedis = new Jedis("192.168.0.106", 6379);
System.out.println("连接成功");
//存储数据到列表中
jedis.lpush("site-list", "Runoob");
jedis.lpush("site-list", "Google");
jedis.lpush("site-list", "Taobao");
// 获取存储的数据并输出
List<String> list = jedis.lrange("site-list", 0 ,2);
for(int i=0; i<list.size(); i++) {
System.out.println("列表项为: "+list.get(i));
}
}
Output:
The use of connection pool connected Redis
And relational databases, create a resource connection Redis database objects is very limited, and each creation and destruction are very time-consuming, it is recommended to use the connection pool Redis connection Redis.
@Test
public void ConnByPoolTest() {
JedisPoolConfig config = new JedisPoolConfig();
//设置最大的连接数
config.setMaxTotal(30);
//设置最大空闲数
config.setMaxIdle(10);
JedisPool pool = new JedisPool(config, "192.168.0.102", 6379);
Jedis jedis = null;
try {
jedis = pool.getResource();
jedis.set("city", "shanghai");
String name = jedis.get("city");
System.out.println(name);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(jedis != null) {
jedis.close();
}
if(pool != null) {
pool.close();
}
}
}