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。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值