Jedis

1、一个对比

MySQLRedis
连接ConnectionJedis
连接池C3P0 等等JedisPool
操作完成关闭连接关闭连接

2、Redis 准备

① 理解 Redis 配置文件中 bind 配置项含义

bind 后面跟的 ip 地址是客户端访问 Redis 时使用的 IP 地址。看下面例子:

bind 值访问方式
127.0.0.1./redis-cli -h 127.0.0.1
192.168.200.100./redis-cli -h 192.168.200.100

② 查看 Linux 系统本机 IP

远程客户端访问 Linux 服务器时不能使用 127.0.0.1,要使用网络上的实际 IP。可以用 ifconfig 命令查看。

③ 将 Redis 配置文件中的 bind 配置项设置为本机 IP。

重启 Redis 服务,客户端登录

1
/usr/local/redis/bin/redis-cli -h 192.168.88.88

[root@ShiGuang ~]# /usr/local/redis/bin/redis-cli -h 192.168.88.88
192.168.88.88:6379>

3、新建一个 Maven 工程

配置 pom.xml 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>

在 test 里面新建一个 java 进行测试

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
package com.atguigu.jedis.test;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

public class MyJedisTest {

// 将连接Redis服务器的IP地址声明为成员变量
private String host = "192.168.88.88";

@Test
public void testJedis() {

// 1.创建Jedis对象
Jedis jedis = new Jedis(host, 6379);

// 2.调用Jedis对象的方法访问Redis服务器
String ping = jedis.ping();
System.out.println("ping = " + ping);

// 3.关闭连接
jedis.close();

}

使用连接池进行测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void testJedisPool() {

// 1.创建JedisPool对象
JedisPool jedisPool = new JedisPool(host, Protocol.DEFAULT_PORT);

// 2.从JedisPool对象中获取一个具体的Jedis对象
Jedis jedis = jedisPool.getResource();

// 3.访问Redis服务器
String ping = jedis.ping();
System.out.println("ping = " + ping);

// 4.关闭连接
jedis.close();
}