Java API 操作Redis

针对 Redis 的 Java 客户端有很多种,具体查看官网信息:https://redis.io/clients#java
本次测试使用 Jedis API,Jedis 使用方便,其 api 方法名称与 redis 命令名称一致。
如果不熟悉 redis 命令,可以参考:《Redis 客户端基本命令》

一、依赖#

Copy
  1. <dependency>
  2. <groupId>redis.clients</groupId>
  3. <artifactId>jedis</artifactId>
  4. <version>2.8.0</version>
  5. </dependency>

二、编码#

Copy
  1. import java.io.IOException;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. import org.junit.Test;
  5. import redis.clients.jedis.HostAndPort;
  6. import redis.clients.jedis.Jedis;
  7. import redis.clients.jedis.JedisCluster;
  8. import redis.clients.jedis.JedisPool;
  9. import redis.clients.jedis.JedisPoolConfig;
  10. public class RedisTest {
  11. private static final String URL = "192.168.2.11";
  12. private static final int PORT = 6379;
  13. /**
  14. * redis 简单操作
  15. */
  16. @Test
  17. public void testJedisPool() {
  18. // 单例
  19. JedisPool pool = new JedisPool(URL, PORT);
  20. Jedis jedis = pool.getResource();
  21. jedis.set("username", "admin");
  22. String value = jedis.get("username");
  23. System.out.println(value);
  24. jedis.close();
  25. }
  26. /**
  27. * redis 带 config 配置操作
  28. */
  29. @Test
  30. public void testJedisPoolAndConfig() {
  31. JedisPoolConfig config = new JedisPoolConfig();
  32. config.setMaxTotal(10);
  33. config.setMinIdle(5);
  34. JedisPool pool = new JedisPool(config, URL, PORT);
  35. Jedis jedis = pool.getResource();
  36. jedis.set("goods", "手提电脑");
  37. String value = jedis.get("goods");
  38. System.out.println(value);
  39. jedis.close();
  40. }
  41. /**
  42. * redis 集群操作
  43. */
  44. @Test
  45. public void testJedisCluster() {
  46. Set<HostAndPort> nodes = new HashSet<>();
  47. nodes.add(new HostAndPort(URL, 6379));
  48. nodes.add(new HostAndPort(URL, 6380));
  49. nodes.add(new HostAndPort(URL, 6381));
  50. nodes.add(new HostAndPort(URL, 6382));
  51. nodes.add(new HostAndPort(URL, 6383));
  52. nodes.add(new HostAndPort(URL, 6384));
  53. // 单例
  54. JedisCluster cluster = new JedisCluster(nodes);
  55. cluster.set("cluster", "hello world");
  56. String value = cluster.get("cluster");
  57. System.out.println(value);
  58. try {
  59. // 当系统关闭时才关闭
  60. cluster.close();
  61. } catch (IOException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. }