spring boot 自学笔记(三) Redis集成—RedisTemplate

spring boot 基于Spring,  Redis集成与Spring大同小异。

文章示例代码均以前篇笔记为基础增加修改,直接上代码:

pom.xml  Redis相关依赖:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  4.     <modelVersion>4.0.0</modelVersion>  
  5.     <groupId>com.vic</groupId>  
  6.     <artifactId>vic</artifactId>  
  7.     <version>0.1.0</version>  
  8.   
  9.     <properties>  
  10.         <java.version>1.7</java.version>  
  11.     </properties>  
  12.       
  13.     <parent>  
  14.         <groupId>org.springframework.boot</groupId>  
  15.         <artifactId>spring-boot-starter-parent</artifactId>  
  16.         <version>1.3.8.RELEASE</version>  
  17.     </parent>  
  18.   
  19.     <dependencies>  
  20.         <!-- spring boot -->  
  21.         <dependency>  
  22.             <groupId>org.springframework.boot</groupId>  
  23.             <artifactId>spring-boot-starter-web</artifactId>  
  24.         </dependency>  
  25.           
  26.         <!-- mybatis -->  
  27.         <dependency>  
  28.             <groupId>org.springframework.boot</groupId>  
  29.             <artifactId>spring-boot-starter-jdbc</artifactId>  
  30.         </dependency>  
  31.   
  32.         <dependency>  
  33.             <groupId>org.mybatis</groupId>  
  34.             <artifactId>mybatis-spring</artifactId>  
  35.             <version>1.2.2</version>  
  36.         </dependency>  
  37.         <dependency>  
  38.             <groupId>org.mybatis</groupId>  
  39.             <artifactId>mybatis</artifactId>  
  40.             <version>3.2.8</version>  
  41.         </dependency>  
  42.   
  43.         <dependency>  
  44.             <groupId>mysql</groupId>  
  45.             <artifactId>mysql-connector-java</artifactId>  
  46.         </dependency>  
  47.   
  48.         <dependency>  
  49.             <groupId>com.mchange</groupId>  
  50.             <artifactId>c3p0</artifactId>  
  51.             <version>0.9.2.1</version>  
  52.         </dependency>  
  53.           
  54.           
  55.         <!-- redis -->  
  56.         <dependency>  
  57.             <groupId>org.springframework.boot</groupId>  
  58.             <artifactId>spring-boot-starter-redis</artifactId>  
  59.   
  60.         </dependency>  
  61.           
  62.         <!--Gson-->    
  63.         <dependency>    
  64.             <groupId>com.google.code.gson</groupId>    
  65.             <artifactId>gson</artifactId>    
  66.         </dependency>    
  67.           
  68.           
  69.     </dependencies>  
  70.     <build>  
  71.         <plugins>  
  72.             <plugin>  
  73.                 <groupId>org.springframework.boot</groupId>  
  74.                 <artifactId>spring-boot-maven-plugin</artifactId>  
  75.             </plugin>  
  76.         </plugins>  
  77.     </build>  
  78. </project>  


application.properties增加redis相关属性:

[plain]  view plain  copy
  1. #datasource  
  2. spring.datasource.jdbcUrl=jdbc:mysql://115.28.92.178:3306/wms?useUnicode\=true&characterEncoding\=utf8;autoReconnect\=true;maxReconnects\=10;connectTimeout\=180000;socketTimeout\=180000  
  3. spring.datasource.user=root  
  4. spring.datasource.password=xx  
  5. spring.datasource.driverClass=com.mysql.jdbc.Driver  
  6. spring.datasource.maxActive=100  
  7. spring.datasource.initialPoolSize=5  
  8. spring.datasource.minPoolSize=5  
  9. spring.datasource.maxPoolSize=20  
  10. spring.datasource.maxStatements=100  
  11. spring.datasource.maxIdleTime=3600  
  12. spring.datasource.acquireIncrement=2  
  13. spring.datasource.acquireRetryAttempts=10  
  14. spring.datasource.acquireRetryDelay=600  
  15. spring.datasource.testConnectionOnCheckin=true  
  16. spring.datasource.idleConnectionTestPeriod=1200  
  17. spring.datasource.checkoutTimeout=100000  
  18.   
  19.   
  20. #redis  
  21. spring.redis.hostName=115.28.92.178  
  22. spring.redis.port=6379    
  23. spring.redis.password=xxx  
  24. spring.redis.pool.maxActive=8    
  25. spring.redis.pool.maxWait=-1    
  26. spring.redis.pool.maxIdle=8    
  27. spring.redis.pool.minIdle=0    
  28. spring.redis.timeout=0  

com.vic.config包中新增RedisConfig.java:

[java]  view plain  copy
  1. /** 
  2.  *  
  3.  * @author vic 
  4.  * @desc redis config bean 
  5.  * 
  6.  */  
  7. @Configuration  
  8. @EnableAutoConfiguration  
  9. public class RedisConfig {  
  10.   
  11.     private static Logger logger = Logger.getLogger(RedisConfig.class);  
  12.       
  13.     @Bean  
  14.     @ConfigurationProperties(prefix="spring.redis")  
  15.     public JedisPoolConfig getRedisConfig(){  
  16.         JedisPoolConfig config = new JedisPoolConfig();  
  17.         return config;  
  18.     }  
  19.       
  20.     @Bean  
  21.     @ConfigurationProperties(prefix="spring.redis")  
  22.     public JedisConnectionFactory getConnectionFactory(){  
  23.         JedisConnectionFactory factory = new JedisConnectionFactory();  
  24.         JedisPoolConfig config = getRedisConfig();  
  25.         factory.setPoolConfig(config);  
  26.         logger.info("JedisConnectionFactory bean init success.");  
  27.         return factory;  
  28.     }  
  29.       
  30.       
  31.     @Bean  
  32.     public RedisTemplate<?, ?> getRedisTemplate(){  
  33.         RedisTemplate<?,?> template = new StringRedisTemplate(getConnectionFactory());  
  34.         return template;  
  35.     }  
  36. }  


OK,此时Reddis已经集成完成,下面来对常用操作做一些封装测试:

新增IRedisService接口定义一些常用操作接口,以及添加实现类RedisServiceImpl,代码如下:


IRedisService.Java

[java]  view plain  copy
  1. /** 
  2.  *  
  3.  * @author vic 
  4.  * @desc redis service 
  5.  */  
  6. public interface IRedisService {  
  7.       
  8.     public boolean set(String key, String value);  
  9.       
  10.     public String get(String key);  
  11.       
  12.     public boolean expire(String key,long expire);  
  13.       
  14.     public <T> boolean setList(String key ,List<T> list);  
  15.       
  16.     public <T> List<T> getList(String key,Class<T> clz);  
  17.       
  18.     public long lpush(String key,Object obj);  
  19.       
  20.     public long rpush(String key,Object obj);  
  21.       
  22.     public String lpop(String key);  
  23.       
  24. }  

RedisServiceImpl.java

[java]  view plain  copy
  1. /** 
  2.  *  
  3.  * @author vic 
  4.  * @desc resdis service 
  5.  * 
  6.  */  
  7. @Service  
  8. public class RedisServiceImpl implements IRedisService{  
  9.   
  10.     @Autowired  
  11.     private RedisTemplate<String, ?> redisTemplate;  
  12.       
  13.     @Override  
  14.     public boolean set(final String key, final String value) {  
  15.         boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
  16.             @Override  
  17.             public Boolean doInRedis(RedisConnection connection) throws DataAccessException {  
  18.                 RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
  19.                 connection.set(serializer.serialize(key), serializer.serialize(value));  
  20.                 return true;  
  21.             }  
  22.         });  
  23.         return result;  
  24.     }  
  25.   
  26.     public String get(final String key){  
  27.         String result = redisTemplate.execute(new RedisCallback<String>() {  
  28.             @Override  
  29.             public String doInRedis(RedisConnection connection) throws DataAccessException {  
  30.                 RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
  31.                 byte[] value =  connection.get(serializer.serialize(key));  
  32.                 return serializer.deserialize(value);  
  33.             }  
  34.         });  
  35.         return result;  
  36.     }  
  37.   
  38.     @Override  
  39.     public boolean expire(final String key, long expire) {  
  40.         return redisTemplate.expire(key, expire, TimeUnit.SECONDS);  
  41.     }  
  42.   
  43.     @Override  
  44.     public <T> boolean setList(String key, List<T> list) {  
  45.         String value = JSONUtil.toJson(list);  
  46.         return set(key,value);  
  47.     }  
  48.   
  49.     @Override  
  50.     public <T> List<T> getList(String key,Class<T> clz) {  
  51.         String json = get(key);  
  52.         if(json!=null){  
  53.             List<T> list = JSONUtil.toList(json, clz);  
  54.             return list;  
  55.         }  
  56.         return null;  
  57.     }  
  58.   
  59.     @Override  
  60.     public long lpush(final String key, Object obj) {  
  61.         final String value = JSONUtil.toJson(obj);  
  62.         long result = redisTemplate.execute(new RedisCallback<Long>() {  
  63.             @Override  
  64.             public Long doInRedis(RedisConnection connection) throws DataAccessException {  
  65.                 RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
  66.                 long count = connection.lPush(serializer.serialize(key), serializer.serialize(value));  
  67.                 return count;  
  68.             }  
  69.         });  
  70.         return result;  
  71.     }  
  72.   
  73.     @Override  
  74.     public long rpush(final String key, Object obj) {  
  75.         final String value = JSONUtil.toJson(obj);  
  76.         long result = redisTemplate.execute(new RedisCallback<Long>() {  
  77.             @Override  
  78.             public Long doInRedis(RedisConnection connection) throws DataAccessException {  
  79.                 RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
  80.                 long count = connection.rPush(serializer.serialize(key), serializer.serialize(value));  
  81.                 return count;  
  82.             }  
  83.         });  
  84.         return result;  
  85.     }  
  86.   
  87.     @Override  
  88.     public String lpop(final String key) {  
  89.         String result = redisTemplate.execute(new RedisCallback<String>() {  
  90.             @Override  
  91.             public String doInRedis(RedisConnection connection) throws DataAccessException {  
  92.                 RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
  93.                 byte[] res =  connection.lPop(serializer.serialize(key));  
  94.                 return serializer.deserialize(res);  
  95.             }  
  96.         });  
  97.         return result;  
  98.     }  
  99.   
  100. }  

其中的JSONUtil类,可下载demo代码查看,其实就是一个JSON的工具类。


在ExampleController中添加测试方法:

[java]  view plain  copy
  1. @RestController  
  2. public class ExampleController {  
  3.   
  4.     @Autowired  
  5.     private IUserService userService;  
  6.       
  7.     @Autowired  
  8.     private IRedisService redisService;  
  9.       
  10.     @RequestMapping("/users")  
  11.     public ResponseModal users(){  
  12.         List<User> users = userService.getAll();  
  13.         ResponseModal modal = new ResponseModal(200,true,"",users);  
  14.         return modal;  
  15.     }  
  16.       
  17.     @RequestMapping("/redis/set")  
  18.     public ResponseModal redisSet(@RequestParam("value")String value){  
  19.         boolean isOk = redisService.set("name", value);  
  20.         return new ResponseModal(isOk ? 200 : 500, isOk, isOk ? "success" : "error" , null);  
  21.     }  
  22.       
  23.     @RequestMapping("/redis/get")  
  24.     public ResponseModal redisGet(){  
  25.         String name = redisService.get("name");  
  26.         return new ResponseModal(200true,"success",name);  
  27.     }  
  28.       
  29. }  


运行Application的main函数

浏览器输入:http://localhost:8080/redis/set?value=vic  响应结果:

{"code":200,"success":true,"message":"success","response":null}

浏览器输入:http://localhost:8080/redis/get  响应结果:

{"code":200,"success":true,"message":"success","response":"vic"}


示例代码下载


转载  http://blog.csdn.net/i_vic/article/details/53081241

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值