RedisTemplate常用集合使用說明

RedisTemplate常用集合使用說明

 在這裏我使用的是spring-boot框架組合的redisTemplate的jar包spring-boot-starter-data-redis,採用POM的方式引入,引入代碼如下:

 

Xml代碼  收藏代碼
  1. <parent>  
  2.     <groupId>org.springframework.boot</groupId>  
  3.     <artifactId>spring-boot-starter-parent</artifactId>  
  4.     <version>1.5.6.RELEASE</version>  
  5. </parent>  
  6.   
  7. <dependencies>  
  8.     <dependency>  
  9.         <groupId>org.springframework.boot</groupId>  
  10.         <artifactId>spring-boot-starter-data-redis</artifactId>  
  11.     </dependency>  
  12.   
  13.     <dependency>  
  14.         <groupId>org.springframework.boot</groupId>  
  15.         <artifactId>spring-boot-starter-test</artifactId>  
  16.     </dependency>  
  17.   
  18.     <dependency>  
  19.         <groupId>org.springframework.boot</groupId>  
  20.         <artifactId>spring-boot-starter-web</artifactId>  
  21.     </dependency>  
  22.   
  23.     <dependency>  
  24.         <groupId>org.springframework.boot</groupId>  
  25.         <artifactId>spring-boot-configuration-processor</artifactId>  
  26.         <optional>true</optional>  
  27.     </dependency>  
  28. </dependencies>  

  RedisTemplate主要支持String,List,Hash,Set,ZSet這幾種方式的參數,其對應的方法分別是opsForValue()、opsForList()、opsForHash()、opsForSet()、opsForZSet()。下面分別介紹這幾個方法的使用。

 

  在介紹之前,首先說下RedisTemplate的序列化方法,在RedisTemplate類下有一個繼承了該類的StringRedisTemplate類,該類主要用於opsForValue()方法的String類型的實現,而且這2個類的內部實現不一樣,如果是使用RedisTemplate類作爲連接Redis的工具類,如果不使用opsForValue方法的話,我們可以這樣初始化序列化方法:

 

Java代碼  收藏代碼
  1. ObjectMapper om = new ObjectMapper();  
  2. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
  3. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  
  4. jackson2JsonRedisSerializer.setObjectMapper(om);  
  5. template.setKeySerializer(template.getStringSerializer());  
  6. template.setValueSerializer(jackson2JsonRedisSerializer);  
  7. template.setHashValueSerializer(jackson2JsonRedisSerializer);  

 如果需要使用opsForValue()方法的話,我們就必須使用如下的序列化方法:

 

 

Java代碼  收藏代碼
  1. ObjectMapper om = new ObjectMapper();  
  2. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
  3. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  
  4. jackson2JsonRedisSerializer.setObjectMapper(om);   
  5. //在使用String的數據結構的時候使用這個來更改序列化方式  
  6. RedisSerializer<String> stringSerializer = new StringRedisSerializer();  
  7. template.setKeySerializer(stringSerializer );  
  8. template.setValueSerializer(stringSerializer );  
  9. template.setHashKeySerializer(stringSerializer );  
  10. template.setHashValueSerializer(stringSerializer );  

   當然如果想使用RedisTemplate方法作爲bean來使用,必須按照如下的方式實現代碼(這裏介紹的都是通過使用spring-boot方式進行使用):

1.  我們可以在application.properties文件定義如下的redis連接:

 

Xml代碼  收藏代碼
  1.     #配置緩存redis  
  2. spring.redis.database=8  
  3. # Redis服務器地址  
  4. spring.redis.host=127.0.0.1  
  5. # Redis服務器連接端口  
  6. spring.redis.port=6379  
  7. # Redis服務器連接密碼(默認爲空)  
  8. spring.redis.password=  
  9. # 連接池最大連接數(使用負值表示沒有限制)  
  10. spring.redis.pool.max-active=8  
  11. # 連接池最大阻塞等待時間(使用負值表示沒有限制)  
  12. spring.redis.pool.max-wait=-1  
  13. # 連接池中的最大空閒連接  
  14. spring.redis.pool.max-idle=8  
  15. # 連接池中的最小空閒連接  
  16. spring.redis.pool.min-idle=0  
  17. # 連接超時時間(毫秒)  
  18. spring.redis.keytimeout=1000  
  19. spring.redis.timeout=0  

2. 使用RedisTemplate類來設置bean文件:

 

 

Java代碼  收藏代碼
  1. import com.fasterxml.jackson.annotation.JsonAutoDetect;  
  2. import com.fasterxml.jackson.annotation.PropertyAccessor;  
  3. import com.fasterxml.jackson.databind.ObjectMapper;  
  4. import org.springframework.beans.factory.annotation.Value;  
  5. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;  
  6. import org.springframework.context.annotation.Bean;  
  7. import org.springframework.context.annotation.Configuration;  
  8. import org.springframework.data.redis.connection.RedisConnectionFactory;  
  9. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;  
  10. import org.springframework.data.redis.core.RedisTemplate;  
  11. import org.springframework.data.redis.core.StringRedisTemplate;  
  12. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;  
  13. import org.springframework.data.redis.serializer.RedisSerializer;  
  14. import org.springframework.data.redis.serializer.StringRedisSerializer;  
  15. import redis.clients.jedis.JedisPoolConfig;  
  16.   
  17. /** 
  18.  * @author liaoyubo 
  19.  * @version 1.0 2017/8/1 
  20.  * @description 
  21.  */  
  22. @Configuration  
  23. public class RedisConfig {  
  24.   
  25.     @Value("${spring.redis.host}")  
  26.     private String hostName;  
  27.     @Value("${spring.redis.port}")  
  28.     private int port;  
  29.     @Value("${spring.redis.password}")  
  30.     private String passWord;  
  31.     @Value("${spring.redis.pool.max-idle}")  
  32.     private int maxIdl;  
  33.     @Value("${spring.redis.pool.min-idle}")  
  34.     private int minIdl;  
  35.     @Value("${spring.redis.database}")  
  36.     private int database;  
  37.     @Value("${spring.redis.keytimeout}")  
  38.     private long keytimeout;  
  39.     @Value("${spring.redis.timeout}")  
  40.     private int timeout;  
  41.   
  42.     /*@Bean 
  43.     public JedisConnectionFactory redisConnectionFactory() { 
  44.         JedisConnectionFactory factory = new JedisConnectionFactory(); 
  45.         factory.setHostName(hostName); 
  46.         factory.setPort(port); 
  47.         factory.setTimeout(timeout); //設置連接超時時間 
  48.         return factory; 
  49.     } 
  50.  
  51.     @Bean 
  52.     public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { 
  53.         StringRedisTemplate template = new StringRedisTemplate(factory); 
  54.         setSerializer(template); //設置序列化工具,這樣ReportBean不需要實現Serializable接口 
  55.         template.afterPropertiesSet(); 
  56.         return template; 
  57.     } 
  58.     private void setSerializer(StringRedisTemplate template) { 
  59.         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); 
  60.         ObjectMapper om = new ObjectMapper(); 
  61.         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 
  62.         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 
  63.         jackson2JsonRedisSerializer.setObjectMapper(om); 
  64.         template.setValueSerializer(jackson2JsonRedisSerializer); 
  65.     }*/  
  66.   
  67.     @Bean  
  68.     public RedisConnectionFactory redisConnectionFactory(){  
  69.         JedisPoolConfig poolConfig=new JedisPoolConfig();  
  70.         poolConfig.setMaxIdle(maxIdl);  
  71.         poolConfig.setMinIdle(minIdl);  
  72.         poolConfig.setTestOnBorrow(true);  
  73.         poolConfig.setTestOnReturn(true);  
  74.         poolConfig.setTestWhileIdle(true);  
  75.         poolConfig.setNumTestsPerEvictionRun(10);  
  76.         poolConfig.setTimeBetweenEvictionRunsMillis(60000);  
  77.         JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);  
  78.         jedisConnectionFactory.setHostName(hostName);  
  79.         if(!passWord.isEmpty()){  
  80.             jedisConnectionFactory.setPassword(passWord);  
  81.         }  
  82.         jedisConnectionFactory.setPort(port);  
  83.         jedisConnectionFactory.setDatabase(database);  
  84.         return jedisConnectionFactory;  
  85.     }  
  86.     @Bean  
  87.     public RedisTemplate<String, Object> redisTemplateObject() throws Exception {  
  88.         RedisTemplate<String, Object> redisTemplateObject = new RedisTemplate<String, Object>();  
  89.         redisTemplateObject.setConnectionFactory(redisConnectionFactory());  
  90.         setSerializer(redisTemplateObject);  
  91.         redisTemplateObject.afterPropertiesSet();  
  92.         return redisTemplateObject;  
  93.     }  
  94.   
  95.   
  96.   
  97.     private void setSerializer(RedisTemplate<String, Object> template) {  
  98.         Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(  
  99.                 Object.class);  
  100.         ObjectMapper om = new ObjectMapper();  
  101.         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
  102.         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  
  103.         jackson2JsonRedisSerializer.setObjectMapper(om);  
  104.         /*template.setKeySerializer(template.getStringSerializer()); 
  105.         template.setValueSerializer(jackson2JsonRedisSerializer); 
  106.         template.setHashValueSerializer(jackson2JsonRedisSerializer);*/  
  107.         //在使用String的數據結構的時候使用這個來更改序列化方式  
  108.         RedisSerializer<String> stringSerializer = new StringRedisSerializer();  
  109.         template.setKeySerializer(stringSerializer );  
  110.         template.setValueSerializer(stringSerializer );  
  111.         template.setHashKeySerializer(stringSerializer );  
  112.         template.setHashValueSerializer(stringSerializer );  
  113.   
  114.     }  
  115.   
  116. }  

 3.  創建啓動類App類

 

 

Java代碼  收藏代碼
  1. import org.springframework.boot.SpringApplication;  
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  3.   
  4. /** 
  5.  * @author liaoyubo 
  6.  * @version 1.0 2017/7/31 
  7.  * @description 
  8.  */  
  9. @SpringBootApplication  
  10. public class App {  
  11.   
  12.     public static void main(String [] args){  
  13.         SpringApplication.run(App.class);  
  14.     }  
  15.   
  16. }  

  通過以上步驟我們就可以以bean的注入方式正常使用RedisTemplate模板類了,如果沒有安裝Redis,請到https://redis.io/download官網下載需要的Redis。下面依次主要介紹RedisTemplate集合以及pipeline、multi的使用,官網地址是http://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/RedisTemplate.html。注入RedisTemplate方法如下:

 

 

 

Java代碼  收藏代碼
  1. @Autowired  
  2. private RedisTemplate<String,Object> redisTemplate;  

 一、pipeline介紹

 

      Pipeline是redis提供的一種通道功能,通常使用pipeline的地方是不需要等待結果立即返回的時候,使用pipeline的好處是處理數據的速度更快因爲它專門開闢了一個管道來處理數據(具體的對比可以參考網上的文章),它是單向的,從客戶端向服務端發送數據,當管道關閉鏈接時將會從服務端返回數據,再次期間是無法獲取到服務端的數據的。

   因爲這個例子的需要,我們把RedisConfig.java類的序列化的方式修改爲:

 

Java代碼  收藏代碼
  1. template.setKeySerializer(template.getStringSerializer());  
  2. template.setValueSerializer(jackson2JsonRedisSerializer);  
  3. template.setHashValueSerializer(jackson2JsonRedisSerializer);  

 下面是一個基本的使用示例:

Java代碼  收藏代碼
  1. import com.springRedis.App;  
  2. import org.junit.Test;  
  3. import org.junit.runner.RunWith;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.boot.test.context.SpringBootTest;  
  6. import org.springframework.dao.DataAccessException;  
  7. import org.springframework.data.redis.connection.RedisConnection;  
  8. import org.springframework.data.redis.core.RedisCallback;  
  9. import org.springframework.data.redis.core.RedisTemplate;  
  10. import org.springframework.test.context.junit4.SpringRunner;  
  11.   
  12.   
  13. /** 
  14.  * @author liaoyubo 
  15.  * @version 1.0 2017/7/31 
  16.  * @description 
  17.  */  
  18.   
  19. @RunWith(SpringRunner.class)  
  20. @SpringBootTest(classes = App.class)  
  21. public class PipelineTest {  
  22.   
  23.     @Autowired  
  24.     private RedisTemplate<String,Object> redisTemplate;  
  25.   
  26.     @Test  
  27.     public void testPipeLine(){  
  28.         redisTemplate.opsForValue().set("a",1);  
  29.         redisTemplate.opsForValue().set("b",2);  
  30.         redisTemplate.executePipelined(new RedisCallback<Object>() {  
  31.             @Override  
  32.             public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {  
  33.                 redisConnection.openPipeline();  
  34.                 for (int i = 0;i < 10;i++){  
  35.                     redisConnection.incr("a".getBytes());  
  36.                 }  
  37.                 System.out.println("a:"+redisTemplate.opsForValue().get("a"));  
  38.                 redisTemplate.opsForValue().set("c",3);  
  39.                 for(int j = 0;j < 20;j++){  
  40.                     redisConnection.incr("b".getBytes());  
  41.                 }  
  42.                 System.out.println("b:"+redisTemplate.opsForValue().get("b"));  
  43.                 System.out.println("c:"+redisTemplate.opsForValue().get("c"));  
  44.                 redisConnection.closePipeline();  
  45.                 return null;  
  46.             }  
  47.         });  
  48.         System.out.println("b:"+redisTemplate.opsForValue().get("b"));  
  49.         System.out.println("a:"+redisTemplate.opsForValue().get("a"));  
  50.     }  
  51.   
  52. }  

 二、multi與exec

 

   這2個方法是RedisTemplate.java類提供的事務方法。在使用這個方法之前必須開啓事務才能正常使用。例子如下:

 

Java代碼  收藏代碼
  1. import com.springRedis.App;  
  2. import org.junit.Test;  
  3. import org.junit.runner.RunWith;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.boot.test.context.SpringBootTest;  
  6. import org.springframework.data.redis.core.RedisTemplate;  
  7. import org.springframework.data.redis.core.ValueOperations;  
  8. import org.springframework.test.context.junit4.SpringRunner;  
  9.   
  10. import java.util.List;  
  11.   
  12. /** 
  13.  * @author liaoyubo 
  14.  * @version 1.0 2017/8/4 
  15.  * @description 
  16.  */  
  17. @RunWith(SpringRunner.class)  
  18. @SpringBootTest(classes = App.class)  
  19. public class MultiTest {  
  20.   
  21.     @Autowired  
  22.     private RedisTemplate<String,Object> redisTemplate;  
  23.   
  24.     @Test  
  25.     public void testMulti(){  
  26.         ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();  
  27.         redisTemplate.setEnableTransactionSupport(true);  
  28.         //在未提交之前是獲取不到值得,同時再次循環報錯  
  29.         while (true){  
  30.             redisTemplate.watch("multiTest");  
  31.             redisTemplate.multi();  
  32.             valueOperations.set("multiTest",1);  
  33.             valueOperations.increment("multiTest",2);  
  34.             Object o = valueOperations.get("multiTest");  
  35.             List list = redisTemplate.exec();  
  36.             System.out.println(list);  
  37.             System.out.println(o);  
  38.         }  
  39.   
  40.     }  
  41.   
  42. }  

           在使用exec()方法的時候,沒有帶入參數,使用的是默認的序列化方法,同時提供了一個exec(RedisSerializer<?> valueSerializer)方法,這個方法可以自己定義序列化方法,如Jackson2JsonRedisSerializer。

 

 

發佈了14 篇原創文章 · 獲贊 5 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章