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

2.String(字符串)

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

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


4.List(列表)

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


5.Set(集合)

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

6.SortedSet(有序集合)

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

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

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


源码请戳​​这里​​。


梅花香自古寒来