Java API 操作Redis
针对 Redis 的 Java 客户端有很多种,具体查看官网信息:https://redis.io/clients#java
本次测试使用 Jedis API,Jedis 使用方便,其 api 方法名称与 redis 命令名称一致。
如果不熟悉 redis 命令,可以参考:《Redis 客户端基本命令》
一、依赖#
- <dependency>
- <groupId>redis.clients</groupId>
- <artifactId>jedis</artifactId>
- <version>2.8.0</version>
- </dependency>
-
二、编码#
- import java.io.IOException;
- import java.util.HashSet;
- import java.util.Set;
- import org.junit.Test;
- import redis.clients.jedis.HostAndPort;
- import redis.clients.jedis.Jedis;
- import redis.clients.jedis.JedisCluster;
- import redis.clients.jedis.JedisPool;
- import redis.clients.jedis.JedisPoolConfig;
-
- public class RedisTest {
-
- private static final String URL = "192.168.2.11";
-
- private static final int PORT = 6379;
-
- /**
- * redis 简单操作
- */
- @Test
- public void testJedisPool() {
- // 单例
- JedisPool pool = new JedisPool(URL, PORT);
- Jedis jedis = pool.getResource();
- jedis.set("username", "admin");
- String value = jedis.get("username");
- System.out.println(value);
- jedis.close();
- }
-
- /**
- * redis 带 config 配置操作
- */
- @Test
- public void testJedisPoolAndConfig() {
- JedisPoolConfig config = new JedisPoolConfig();
- config.setMaxTotal(10);
- config.setMinIdle(5);
-
- JedisPool pool = new JedisPool(config, URL, PORT);
- Jedis jedis = pool.getResource();
- jedis.set("goods", "手提电脑");
- String value = jedis.get("goods");
- System.out.println(value);
- jedis.close();
- }
-
- /**
- * redis 集群操作
- */
- @Test
- public void testJedisCluster() {
- Set<HostAndPort> nodes = new HashSet<>();
- nodes.add(new HostAndPort(URL, 6379));
- nodes.add(new HostAndPort(URL, 6380));
- nodes.add(new HostAndPort(URL, 6381));
- nodes.add(new HostAndPort(URL, 6382));
- nodes.add(new HostAndPort(URL, 6383));
- nodes.add(new HostAndPort(URL, 6384));
- // 单例
- JedisCluster cluster = new JedisCluster(nodes);
- cluster.set("cluster", "hello world");
- String value = cluster.get("cluster");
- System.out.println(value);
- try {
- // 当系统关闭时才关闭
- cluster.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-