标准访问方式
创建基础的Maven工程并向pom.xml文件中添加所需的依赖。
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
在Redis主服务器上开启远程访问,并设置防火墙放行对应的服务端口。
# zone为作用域 add-port=6379/tcp为添加的端口号及通讯协议 permanent永久有效
firewall-cmd --zone=public --add-port=6379/tcp --permanent
配置完成后重启防火墙。
firewall-cmd --reload
也可以直接关闭防火墙一劳永逸(不推荐)。
# 暂时关闭防火墙
systemctl stop firewalld.service
# 永久关闭防火墙
systemctl disable firewalld.service
编写测试方法代码。
@Test
public void testJedis() {
//获取Jedis对象,将所有redis操作封装到该类中
//默认连接为本地:localhost,端口号为:6379
Jedis jedis = new Jedis("192.168.112.66", 6379);
//Jedis完成对key的操作
System.out.println(jedis.keys("*"));
//判断k1是否存在
System.out.println(jedis.exists("k1"));
//对String类型的操作
jedis.set("name", "刘德华");
System.out.println(jedis.get("name"));
System.out.println(jedis.setnx("age", "张学友"));
//对Hash类型的操作
Map<String, String> map = new HashMap<>();
map.put("name", "彭于晏");
map.put("age", "18");
map.put("sex", "男");
jedis.hset("people", map);
System.out.println(jedis.hgetAll("people"));
//关闭Jedis对象连接
jedis.close();
}
连接池访问方式
编写测试方法代码。
@Test
public void testPool() {
//创建jedis连接池的配置对象
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(10); //连接的最大数量
jedisPoolConfig.setMinIdle(5); //连接的最小空闲值
jedisPoolConfig.setMaxIdle(8); //连接的最大空闲值
jedisPoolConfig.setTestOnBorrow(true); //获取jedis对象时,校验其可用性
jedisPoolConfig.setMaxWaitMillis(3000); //设置等待时间
//创建jedis连接池
JedisPool jedisPool = new JedisPool(jedisPoolConfig, "192.168.112.66", 6379);
//获取jedis的连接对象
Jedis jedis = jedisPool.getResource();
System.out.println(jedis.keys("*"));
//将连接归还给连接池
jedis.close();
}
集群访问方式
编写测试方法代码。
@Test
public void testColony() {
//配置redis集群
Set<HostAndPort> nodes = new HashSet<>();
nodes.add(new HostAndPort("192.168.112.66", 7001));
nodes.add(new HostAndPort("192.168.112.66", 7002));
nodes.add(new HostAndPort("192.168.112.66", 7003));
nodes.add(new HostAndPort("192.168.112.66", 7004));
nodes.add(new HostAndPort("192.168.112.66", 7005));
nodes.add(new HostAndPort("192.168.112.66", 7006));
//获取jedis链接对象
JedisCluster jedisCluster = new JedisCluster(nodes);
//jedis完成对redis操作
jedisCluster.set("k1", "v1");
System.out.println(jedisCluster.get("k1"));
//关闭jedis对象
jedisCluster.close();
}