Java操作Redis数据

  Redis 是完全开源免费的,遵守BSD协议,先进的key - value持久化产品。它通常被称为数据结构服务器,因为值(value)可以是 字符串(String)哈希(Map),列表(list)集合(sets) 和 有序集合(sorted sets)等类型。下面是使用spring-data-redis分别针对key和value的操作。

1.Key(键)

  1. public class KeysTest extends RedisCommon {
  2. private static StringRedisTemplate template;
  3. private static String key = "key1";
  4.  
  5. public static void main(String[] args) {
  6. log.info("-----------Starting Redis keys testing-----------");
  7. ApplicationContext ctx = SpringApplication.run(KeysTest.class, args);
  8. template = ctx.getBean(StringRedisTemplate.class);
  9. KeysTest keysTest = ctx.getBean(KeysTest.class);
  10. keysTest.initValue();
  11.  
  12. log.info("KeysTest @##@ randomKey: " + template.randomKey());
  13.  
  14. keysTest.expireKey(key, 2);
  15. // keysTest.persistKey(key, 2);
  16.  
  17. String newkey = "newKey";
  18. // template.rename(key, newkey);
  19. template.renameIfAbsent(key, newkey);
  20.  
  21. Set<String> keys = template.keys("*");
  22. log.info("KeysTest @##@ keys:" + keys);
  23. for (String key : keys) {
  24. log.info("KeysTest @##@ " + key + " expire:"
  25. + template.getExpire(key));
  26. // template.getExpire(key, TimeUnit.SECONDS);
  27. }
  28.  
  29. int dbIndex = 1;// ref:http://redisdoc.com/key/move.html
  30. log.info("KeysTest @##@ move " + key + " to db" + dbIndex + ": "
  31. + template.move(key, 1));
  32.  
  33. // template.delete(key);
  34. template.delete(keys);
  35. log.info("KeysTest @##@ delete keys: " + keys);
  36.  
  37. // template.exec();
  38. // template.multi();
  39. // template.discard();
  40.  
  41. // template.slaveOf(host, port);
  42. // template.slaveOfNoOne();
  43.  
  44. // template.watch(key);
  45. // template.watch(keys);
  46. // template.unwatch();
  47. log.info("-----------End Redis keys testing-----------");
  48. }
  49.  
  50. public void initValue() {
  51. String value = "hello,redis";
  52. template.opsForValue().set(key, value);
  53. Set<String> keys = new HashSet<String>() {
  54. private static final long serialVersionUID = -4402948387930279259L;
  55. {
  56. this.add("key2");
  57. this.add("key3");
  58. this.add("key4");
  59. }
  60. };
  61. try {
  62. byte[] bytes = template.dump(key);
  63. log.info("KeysTest # key dump:" + new String(bytes));
  64. for (String k : keys) {
  65. template.restore(k, bytes, 0, TimeUnit.SECONDS);
  66. }
  67. } catch (Exception e) {
  68. e.printStackTrace();
  69. }
  70. }
  71.  
  72. public boolean expireKey(String key, long expiretime) {
  73. log.info("KeysTest @##@ has " + key + " : " + template.hasKey(key));
  74. log.info("KeysTest @##@ expire " + key + " for " + expiretime
  75. + " seconds : "
  76. + template.expire(key, expiretime, TimeUnit.SECONDS));
  77. // template.expireAt(key, new Date());
  78. try {
  79. Thread.sleep((expiretime + 1) * 1000);
  80. } catch (InterruptedException e) {
  81. e.printStackTrace();
  82. }
  83. boolean result = template.hasKey(key);
  84. log.info("KeysTest @##@ has " + key + " : " + result);
  85. return result;
  86. }
  87.  
  88. public boolean persistKey(String key, long expiretime) {
  89. log.info("KeysTest @##@ has " + key + " : " + template.hasKey(key));
  90. log.info("KeysTest @##@ expire " + key + " for " + expiretime
  91. + " seconds : "
  92. + template.expire(key, expiretime, TimeUnit.SECONDS));
  93. log.info("KeysTest @##@ persist " + key + " : " + template.persist(key));
  94. try {
  95. Thread.sleep((expiretime + 1) * 1000);
  96. } catch (InterruptedException e) {
  97. e.printStackTrace();
  98. }
  99. return template.hasKey(key);
  100. }
  101.  
  102. }

2.String(字符串)

  1. public class StringsTest extends RedisCommon {
  2. private static StringRedisTemplate template;
  3. private static String key = "strKey";
  4.  
  5. public static void main(String[] args) throws InterruptedException {
  6. log.info("-----------Starting Redis Strings testing-----------");
  7. ApplicationContext ctx = SpringApplication.run(StringsTest.class, args);
  8. template = ctx.getBean(StringRedisTemplate.class);
  9. StringsTest stringsTest = ctx.getBean(StringsTest.class);
  10.  
  11. String value = "hello, redis";
  12. template.opsForValue().set(key, value);
  13. log.info("StringsTest @##@ " + key + "'s value: " + template.opsForValue().get(key));
  14. log.info("StringsTest @##@ " + key + "'s size: " + template.opsForValue().size(key));
  15.  
  16. stringsTest.getRange(key, 0, 5);
  17.  
  18. template.opsForValue().getAndSet(key, "hello, redis world");
  19. log.info("StringsTest @##@ " + key + "'s value after getAndSet: " + template.opsForValue().get(key));
  20.  
  21. stringsTest.multiOperation();
  22.  
  23. stringsTest.incrementDouble();
  24.  
  25. stringsTest.incrementLong();
  26. }
  27.  
  28. public void getRange(String key, int start, int end){
  29. log.info("StringsTest @##@ " + key + "'s value: " + template.opsForValue().get(key));
  30. log.info("StringsTest @##@ " + key + " range from "+start +" to " + end +" value is: " + template.opsForValue().get(key, start, end));
  31. }
  32.  
  33. public void multiOperation(){
  34. Map<String, String> m = new HashMap<>();
  35. Set<String> keys = new HashSet<>();
  36. for(int i=0;i< 4;i++){
  37. m.put("key" + i, "value" + i);
  38. keys.add("key" + i);
  39. }
  40. template.opsForValue().multiSet(m);
  41. log.info("StringsTest @##@ multiSet : done.");
  42. log.info("StringsTest @##@ multiGet : " + template.opsForValue().multiGet(keys));
  43. }
  44.  
  45. public void incrementDouble() {
  46. String hashKey = UUID.randomUUID().toString();
  47. Double value1 = template.opsForValue().increment(hashKey, 30.5d);
  48. log.info(hashKey + " has value :" + value1);
  49. double d = 30.2d;
  50. Double value2 = template.opsForValue().increment(hashKey, d);
  51. log.info(hashKey + " has value: " + value2 + ", after increment " + d);
  52. }
  53.  
  54. public void incrementLong() {
  55. String hashKey = UUID.randomUUID().toString();
  56. long value1 = template.opsForValue().increment(hashKey, 30l);
  57. log.info(hashKey + " has value :" + value1);
  58. long l = 25l;
  59. long value2 = template.opsForValue().increment(hashKey, l);
  60. log.info(hashKey + " has value: " + value2 + ", after increment " + l);
  61. }
  62. }

3.Hash(哈希表)

  1. public class HashTest extends RedisCommon {
  2. private static RedisTemplate<String, Map<String, UserInfo>> userTemplate;
  3. private static RedisTemplate<String, Map<String, Double>> doubleTemplate;
  4. private static RedisTemplate<String, Map<String, Long>> longTemplate;
  5. private static String key = "UserInfo";
  6.  
  7. public static void main(String[] args) throws InterruptedException {
  8. log.info("-----------Starting Redis hash testing-----------");
  9. ApplicationContext ctx = SpringApplication.run(HashTest.class, args);
  10. RedisConnectionFactory connectionFactory = ctx
  11. .getBean(RedisConnectionFactory.class);
  12. userTemplate = new RedisTemplate<>();
  13. userTemplate.setConnectionFactory(connectionFactory);
  14. userTemplate.setKeySerializer(userTemplate.getStringSerializer());
  15. userTemplate.setHashKeySerializer(userTemplate.getStringSerializer());
  16. userTemplate
  17. .setHashValueSerializer(new JacksonJsonRedisSerializer<UserInfo>(
  18. UserInfo.class));
  19. userTemplate.afterPropertiesSet();
  20.  
  21. doubleTemplate = new RedisTemplate<>();
  22. doubleTemplate.setConnectionFactory(connectionFactory);
  23. doubleTemplate.setKeySerializer(doubleTemplate.getStringSerializer());
  24. doubleTemplate.setHashKeySerializer(doubleTemplate.getStringSerializer());
  25. doubleTemplate.setHashValueSerializer(doubleTemplate.getDefaultSerializer());
  26. doubleTemplate.afterPropertiesSet();
  27.  
  28. longTemplate = new RedisTemplate<>();
  29. longTemplate.setConnectionFactory(connectionFactory);
  30. longTemplate.setKeySerializer(longTemplate.getStringSerializer());
  31. longTemplate.setHashKeySerializer(longTemplate.getStringSerializer());
  32. longTemplate.setHashValueSerializer(new LongSerializer());
  33. longTemplate.afterPropertiesSet();
  34.  
  35. HashTest hashTest = ctx.getBean(HashTest.class);
  36. // hashTest.insert();
  37. // hashTest.batchInsert();
  38. // hashTest.insertIfAbsent();
  39. // hashTest.findAll();
  40. // hashTest.findOne();
  41. // hashTest.findAllKeys();
  42. // hashTest.incrementDouble();
  43. hashTest.incrementLong();
  44. }
  45.  
  46. public void insert() {
  47. UserInfo info = new UserInfo();
  48. info.setName("Tomy");
  49. info.setAge(20);
  50. info.setBirthday(new Date());
  51. info.setId(UUID.randomUUID().toString());
  52. userTemplate.opsForHash().put(key, info.getId(), info);
  53. log.info("insert User[" + info + "] success!");
  54. log.info("User Hash size is : " + userTemplate.opsForHash().size(key));
  55. }
  56.  
  57. public void batchInsert() {
  58. Map<String, UserInfo> users = new HashMap<>();
  59. for (int i = 1; i <= 3; i++) {
  60. UserInfo info = new UserInfo();
  61. info.setName("Tomy" + i);
  62. info.setAge(20 + i);
  63. info.setBirthday(new Date());
  64. info.setId(UUID.randomUUID().toString());
  65. users.put(info.getId(), info);
  66. }
  67. userTemplate.opsForHash().putAll(key, users);
  68. log.info("batchInsert Users[" + users + "] success!");
  69. log.info("User Hash size is : " + userTemplate.opsForHash().size(key));
  70. }
  71.  
  72. public void insertIfAbsent() {
  73. UserInfo info = new UserInfo();
  74. info.setName("Tomy4");
  75. info.setAge(20);
  76. info.setBirthday(new Date());
  77. info.setId(UUID.randomUUID().toString());
  78. userTemplate.opsForHash().putIfAbsent(key, info.getId(), info);
  79. log.info("insertIfAbsent User[" + info + "] success!");
  80. log.info("User Hash size is : " + userTemplate.opsForHash().size(key));
  81. }
  82.  
  83. public void findAll() {
  84. Map<Object, Object> users = userTemplate.opsForHash().entries(key);
  85. log.info("All User[" + users + "]");
  86. log.info("findAll User size is : " + users.size());
  87. }
  88.  
  89. public UserInfo findOne() {
  90. String hashKey = "2ca66275-88ab-49e5-8651-b987e55d9347";
  91. Object userInfo = userTemplate.opsForHash().get(key, hashKey);
  92. // boolean have = userTemplate.opsForHash().hasKey(hashKey, hashKey);
  93. log.info("find one : " + userInfo);
  94. return userInfo != null ? (UserInfo) userInfo : null;
  95. }
  96.  
  97. public Set<Object> findAllKeys() {
  98. Set<Object> users = userTemplate.opsForHash().keys(key);
  99. log.info("find : " + users.size() + " users :" + users);
  100. return users;
  101. }
  102.  
  103. public void scan() {
  104. userTemplate.opsForHash().scan(key, ScanOptions.NONE);
  105. }
  106.  
  107. public void incrementDouble() {
  108. String hashKey = UUID.randomUUID().toString();
  109. Double value1 = doubleTemplate.opsForHash().increment(key, hashKey,
  110. Double.valueOf("30"));
  111. log.info(key + ":" + hashKey + " has value :" + value1);
  112. Double delta = Double.valueOf("30.3");
  113. Double value2 = doubleTemplate.opsForHash().increment(key, hashKey, delta);
  114. log.info(key + ":" + hashKey + " has value: " + value2 + ", after increment " + delta);
  115. }
  116.  
  117. public void incrementLong() {
  118. String hashKey = UUID.randomUUID().toString();
  119. long value1 = doubleTemplate.opsForHash().increment(key, hashKey, 30l);
  120. log.info(key + ":" + hashKey + " has value :" + value1);
  121. long delta = 20l;
  122. long value2 = doubleTemplate.opsForHash().increment(key, hashKey, delta);
  123. log.info(key + ":" + hashKey + " has value: " + value2 + ", after increment " + delta);
  124. }
  125.  
  126. }

4.List(列表)

  1. public class ListsTest extends RedisCommon {
  2. private static RedisTemplate<String, UserInfo> userTemplate;
  3.  
  4. public static void main(String[] args) throws InterruptedException {
  5. log.info("-----------Starting Redis Lists testing-----------");
  6. ApplicationContext ctx = SpringApplication.run(ListsTest.class, args);
  7. RedisConnectionFactory connectionFactory = ctx
  8. .getBean(RedisConnectionFactory.class);
  9. userTemplate = new RedisTemplate<>();
  10. userTemplate.setConnectionFactory(connectionFactory);
  11. userTemplate.setKeySerializer(userTemplate.getStringSerializer());
  12. userTemplate.setValueSerializer(new JacksonJsonRedisSerializer<UserInfo>(
  13. UserInfo.class));
  14. userTemplate.afterPropertiesSet();
  15.  
  16. String key = "UserInfo";
  17.  
  18. ListsTest listsTest = ctx.getBean(ListsTest.class);
  19. listsTest.leftpush(key);
  20. listsTest.leftpushBatch(key);
  21. listsTest.leftpop(key);
  22. listsTest.rightPopAndLeftPush(key);
  23. }
  24.  
  25. public void leftpush(String key) {
  26. int size = 10;
  27. for(int i = 0; i < size; i++){
  28. UserInfo info = new UserInfo();
  29. info.setName("Tomy" + i);
  30. info.setAge(20 + i);
  31. info.setBirthday(new Date());
  32. info.setId(UUID.randomUUID().toString());
  33. userTemplate.opsForList().leftPush(key, info);
  34. //userTemplate.opsForList().leftPush(key, pivot, value)
  35. //userTemplate.opsForList().leftPushIfPresent(key, value)
  36. //userTemplate.opsForList().rightPush(key, pivot, value)
  37. //userTemplate.opsForList().rightPushIfPresent(key, value)
  38. }
  39. log.info("insert [" + size + "] User success! " + key + "'s size is:" + userTemplate.opsForList().size(key));
  40. }
  41.  
  42. public void leftpushBatch(String key){
  43. int size = 20;
  44. List<UserInfo> users = new ArrayList<>();
  45. for(int i = 10; i < size; i++){
  46. UserInfo info = new UserInfo();
  47. info.setName("Tomy" + i);
  48. info.setAge(20 + i);
  49. info.setBirthday(new Date());
  50. info.setId(UUID.randomUUID().toString());
  51. users.add(info);
  52. }
  53. userTemplate.opsForList().leftPushAll(key, users.toArray(new UserInfo[users.size()]));
  54. //userTemplate.opsForList().rightPushAll(key, (UserInfo[])users.toArray());
  55. log.info("batchinsert [" + users.size() + "] User success! " + key + "'s size is:" + userTemplate.opsForList().size(key));
  56. }
  57.  
  58. public void leftpop(String key){
  59. UserInfo userInfo = userTemplate.opsForList().leftPop(key, 2, TimeUnit.SECONDS);
  60. //userTemplate.opsForList().leftPop(key);
  61. AtomicInteger ai = new AtomicInteger(0);
  62. while(userInfo != null){
  63. ai.incrementAndGet();
  64. userInfo = userTemplate.opsForList().leftPop(key, 2, TimeUnit.SECONDS);
  65. }
  66. log.info("pop [" + ai.get() + "] Users from " + key);
  67. }
  68.  
  69. public void rightPopAndLeftPush(String srcKey){
  70. String destinationKey = "destinationKey";
  71. log.info("srcKey [" + srcKey + "]'s size : " + userTemplate.opsForList().size(srcKey));
  72. log.info("destKey [" + destinationKey + "]'s size : " + userTemplate.opsForList().size(destinationKey));
  73. UserInfo userInfo = userTemplate.opsForList().rightPopAndLeftPush(srcKey, destinationKey);
  74. while(userInfo != null){
  75. userInfo = userTemplate.opsForList().rightPopAndLeftPush(srcKey, destinationKey, 2, TimeUnit.SECONDS);
  76. }
  77. log.info("After rightPopAndLeftPush destKey [" + destinationKey + "]'s size : " + userTemplate.opsForList().size(destinationKey));
  78. }
  79.  
  80. }

5.Set(集合)

  1. public class SetTest extends RedisCommon {
  2.  
  3. public static void main(String[] args) throws InterruptedException {
  4. log.info("-----------Starting Redis Set testing-----------");
  5. ApplicationContext ctx = SpringApplication.run(SetTest.class, args);
  6. StringRedisTemplate st = ctx.getBean(StringRedisTemplate.class);
  7. String key = "SetKey";
  8. String destKey = "DestKey";
  9. String[] values = new String[]{"value1","value2","value3","value4","value5","value6","value7"};
  10. log.info("SetKey add [" + st.opsForSet().add(key, values ) + "] values ");
  11. log.info("SetKey's member " + st.opsForSet().members(key));
  12. String value5 = "value5";
  13. log.info(value5 + " is member of SetKey's : " + st.opsForSet().isMember(key, value5));
  14. log.info("SetKey's randomMember [" + st.opsForSet().randomMember(key) + "]");
  15. log.info("SetKey's size: " + st.opsForSet().size(key));
  16.  
  17. String[] subValues = new String[]{"value1","value2","value3"};
  18. log.info("SetKey remove " + st.opsForSet().remove(key, subValues) + " members");
  19. log.info("SetKey's size: " + st.opsForSet().size(key));
  20.  
  21. log.info("SetKey move to DestKey: " + st.opsForSet().move(key, value5, destKey));
  22. log.info("SetKey's size: " + st.opsForSet().size(key));
  23. log.info("DestKey size: " + st.opsForSet().size(destKey));
  24.  
  25. String popValue = st.opsForSet().pop(key);
  26. log.info("SetKey move to DestKey: " + st.opsForSet().move(key, popValue, destKey));
  27. log.info("SetKey's size: " + st.opsForSet().size(key));
  28. log.info("DestKey size: " + st.opsForSet().size(destKey));
  29.  
  30. //st.opsForSet().difference(key, destKey);
  31. //st.opsForSet().differenceAndStore(key, otherKeys, destKey);
  32.  
  33. //st.opsForSet().intersect(key, destKey);
  34. //st.opsForSet().intersectAndStore(key, otherKey, destKey);
  35. }
  36.  
  37. }

6.SortedSet(有序集合)

  1. public class ZSetTest extends RedisCommon {
  2.  
  3. public static void main(String[] args) throws InterruptedException {
  4. log.info("-----------Starting Redis ZSet testing-----------");
  5. ApplicationContext ctx = SpringApplication.run(ZSetTest.class, args);
  6. StringRedisTemplate st = ctx.getBean(StringRedisTemplate.class);
  7. String key = "ZSetKey";
  8. Set<TypedTuple<String>> values = new HashSet<>();
  9. for (int i = 0; i < 10; i++) {
  10. TypedTuple<String> tuple = new DefaultTypedTuple<String>("value-"
  11. + i, 12d + i);
  12. values.add(tuple);
  13. }
  14. // log.info("SetKey add [" + st.opsForZSet().add(key, values) + "] values");
  15. //st.opsForZSet().add(key, value, score)
  16. //st.opsForZSet().incrementScore(key, value, delta)
  17. log.info("SetKey has [" + st.opsForZSet().size(key) + "] values");
  18.  
  19. double start = 15d;
  20. double end = 18d;
  21. log.info("SetKey between " + start + " and " + end + " have " + st.opsForZSet().count(key, start, end));
  22.  
  23. long s = 1;
  24. long e = 5;
  25. log.info("SetKey range from " + s + " to " + e + " have " + st.opsForZSet().range(key, s, e));
  26. //st.opsForZSet().rangeByScore(key, min, max, offset, count)
  27. //st.opsForZSet().rangeByScoreWithScores(key, min, max)
  28. //st.opsForZSet().rangeByScoreWithScores(key, min, max, offset, count)
  29. //st.opsForZSet()
  30.  
  31. String member = "value-5";
  32. log.info(member + "'s rank is " + st.opsForZSet().rank(key, member) + " in SetKey.");
  33.  
  34. log.info("Remove " + member + " from SetKey : " + st.opsForZSet().remove(key, member));
  35.  
  36. // st.opsForZSet().removeRange(key, start, end)
  37. // st.opsForZSet().removeRangeByScore(key, min, max)
  38. // st.opsForZSet().reverseRange(key, start, end)
  39. // st.opsForZSet().reverseRangeByScore(key, min, max)
  40. // st.opsForZSet().reverseRangeByScoreWithScores(key, min, max)
  41. // st.opsForZSet().reverseRank(key, o)
  42. // st.opsForZSet().unionAndStore(key, otherKeys, destKey)
  43. // st.opsForZSet().unionAndStore(key, otherKey, destKey)
  44. }
  45.  
  46. }

7.Pub/Sub(发布/订阅)

  1. public class TopicTest extends RedisCommon {
  2. private static String topicName = "Topic:chat";
  3.  
  4. @Bean
  5. RedisMessageListenerContainer container(
  6. RedisConnectionFactory connectionFactory,
  7. MessageListenerAdapter listenerAdapter) {
  8. RedisMessageListenerContainer container = new RedisMessageListenerContainer();
  9. container.setConnectionFactory(connectionFactory);
  10. container.addMessageListener(listenerAdapter, new PatternTopic(topicName));
  11. //container.addMessageListener(listenerAdapter, new ChannelTopic(topicName));
  12. return container;
  13. }
  14.  
  15. @Bean
  16. MessageListenerAdapter listenerAdapter(Receiver receiver) {
  17. return new MessageListenerAdapter(receiver, "receiveMessage");
  18. }
  19.  
  20. @Bean
  21. Receiver receiver(@Value("Receiver-1") String name) {
  22. return new Receiver(name);
  23. }
  24.  
  25. public static void main(String[] args) throws InterruptedException {
  26. log.info("-----------Starting Redis Topic testing-----------");
  27. ApplicationContext ctx = SpringApplication.run(TopicTest.class, args);
  28. StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
  29. template.convertAndSend(topicName, "Hello from Redis!");
  30. }
  31.  
  32. static class Receiver {
  33. private String name;
  34.  
  35. @Autowired
  36. public Receiver(String name) {
  37. this.name = name;
  38. }
  39.  
  40. public void receiveMessage(String message) {
  41. log.info(name + " received <" + message + ">");
  42. }
  43. }
  44.  
  45. }

源码请戳这里

原文地址:https://www.cnblogs.com/zhuyeshen/p/11430760.html