springCloud 使用redisTemplate

1、springboot配置文件application.yml

[html]  view plain  copy
  1. #端口  
  2. server:  
  3.   port: 8080  
  4.   
  5. #模板页面  
  6. #注释的部分是Thymeleaf默认的配置,如有其它需求可以自行更改  
  7. spring.thymeleaf.cache: false  
  8. spring.thymeleaf.prefix: classpath:/templates/  
  9. spring.thymeleaf.suffix: .html  
  10. spring.thymeleaf.mode: LEGACYHTML5  
  11. spring.thymeleaf.encoding: UTF-8  
  12. spring.thymeleaf.content-type: text/html  
  13.   
  14.   
  15. #spring-boot整合单机版redis redis作为缓存  
  16. spring.redis.hostName: 192.168.1.103  
  17. spring.redis.port: 6379  
  18. spring.redis.password: xuan123456  
  19. spring.redis.database: 2 #默认使用db0  
  20. spring.redis.timeout: 0  
  21. spring.redis.pool.max-active: 8  
  22. spring.redis.pool.max-wait: -1  
  23. spring.redis.pool.max-idle: 8  
  24. spring.redis.pool.min-idle: 0  
  25.   
  26.   
  27.   
  28.   
  29. ##数据源一  
  30. #spring:  
  31. #      datasource:  
  32. #          driverClass: com.mysql.jdbc.Driver  
  33. #          url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8  
  34. #          username: xuan  
  35. #          password: 123456  
  36. #数据源二  
  37. spring:  
  38.       datasource:  
  39.           url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8  
  40.           username: xuan  
  41.           password: 123456  
  42.           # 使用druid数据源  
  43.           type: com.alibaba.druid.pool.DruidDataSource  
  44.           driver-class-name: com.mysql.cj.jdbc.Driver  
  45.           filters: stat  
  46.           maxActive: 20  
  47.           initialSize: 1  
  48.           maxWait: 60000  
  49.           minIdle: 1  
  50.           timeBetweenEvictionRunsMillis: 60000  
  51.           minEvictableIdleTimeMillis: 300000  
  52.           validationQuery: select 'x'  
  53.           testWhileIdle: true  
  54.           testOnBorrow: false  
  55.           testOnReturn: false  
  56.           poolPreparedStatements: true  
  57.           maxOpenPreparedStatements: 20  
  58.   
  59.   
  60.   
  61. #spring-boot整合mybatis  
  62. mybatis:  
  63.   #config-location: classpath:/mapper/config/mybatisConfig.xml #可以注射掉,没用到该配置文件  
  64.   mapper-locations: classpath:/mapper/*Mapper.xml  
  65.   #type-aliases-package: com.xuan.entity  

2、maven配置文件加入依赖:

[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.   
  6.     <groupId>com.xuan</groupId>  
  7.     <artifactId>myspringboot</artifactId>  
  8.     <version>0.0.1-SNAPSHOT</version>  
  9.     <packaging>jar</packaging>  
  10.   
  11.     <name>myspringboot</name>  
  12.     <description>Demo project for Spring Boot</description>  
  13.   
  14.     <parent>  
  15.         <groupId>org.springframework.boot</groupId>  
  16.         <artifactId>spring-boot-starter-parent</artifactId>  
  17.         <version>1.5.8.RELEASE</version>  
  18.         <relativePath/> <!-- lookup parent from repository -->  
  19.     </parent>  
  20.   
  21.     <properties>  
  22.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  23.         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
  24.         <java.version>1.8</java.version>  
  25.   
  26.         <mybatis.generator.version>1.3.2</mybatis.generator.version>  
  27.         <mysql.connector.java.version>6.0.6</mysql.connector.java.version>  
  28.   
  29.   
  30.         <!-- Used by MyBatis Generator to Generate Codes -->  
  31.         <!-- 运行命令: mvn mybatis-generator:generate -e -->  
  32.         <!--<classPathEntry.mysql.location>${basedir}/target/${project.artifactId}/WEB-INF/lib/mysql-connector-java-${mysql.connector.java.version}.jar</classPathEntry.mysql.location>-->  
  33.         <classPathEntry.mysql.location>/Users/chenqixuan/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar</classPathEntry.mysql.location>  
  34.         <javaModelGenerator.targetProject>${basedir}/src/main/java</javaModelGenerator.targetProject>  
  35.         <sqlMapGenerator.targetProject>${basedir}/src/main/resources</sqlMapGenerator.targetProject>  
  36.         <javaClientGenerator.targetProject>${basedir}/src/main/java</javaClientGenerator.targetProject>  
  37.         <mybatis.generator.configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</mybatis.generator.configurationFile>  
  38.         <mybatis.generator.overwrite>true</mybatis.generator.overwrite>  
  39.     </properties>  
  40.   
  41.     <dependencies>  
  42.   
  43.         <!--eureka server -->  
  44.         <!--<dependency>-->  
  45.             <!--<groupId>org.springframework.cloud</groupId>-->  
  46.             <!--<artifactId>spring-cloud-starter-eureka-server</artifactId>-->  
  47.         <!--</dependency>-->  
  48.   
  49.         <!-- springboot整合redis -->  
  50.         <dependency>  
  51.             <groupId>org.springframework.boot</groupId>  
  52.             <artifactId>spring-boot-starter-data-redis</artifactId>  
  53.         </dependency>  
  54.         <!-- springboot整合mybatis -->  
  55.         <dependency>  
  56.             <groupId>org.mybatis.spring.boot</groupId>  
  57.             <artifactId>mybatis-spring-boot-starter</artifactId>  
  58.             <version>1.3.1</version>  
  59.         </dependency>  
  60.         <!-- mysql jdbc驱动 -->  
  61.         <dependency>  
  62.             <groupId>mysql</groupId>  
  63.             <artifactId>mysql-connector-java</artifactId>  
  64.             <version>${mysql.connector.java.version}</version>  
  65.         </dependency>  
  66.         <dependency>  
  67.             <groupId>org.springframework.boot</groupId>  
  68.             <artifactId>spring-boot-starter-jdbc</artifactId>  
  69.         </dependency>  
  70.         <!-- alibaba的druid数据库连接池 -->  
  71.         <dependency>  
  72.             <groupId>com.alibaba</groupId>  
  73.             <artifactId>druid</artifactId>  
  74.             <version>1.0.11</version>  
  75.         </dependency>  
  76.   
  77.         <dependency>  
  78.             <groupId>org.springframework.boot</groupId>  
  79.             <artifactId>spring-boot-starter-web</artifactId>  
  80.         </dependency>  
  81.   
  82.         <!-- 模板页面 -->  
  83.         <dependency>  
  84.             <groupId>org.springframework.boot</groupId>  
  85.             <artifactId>spring-boot-starter-thymeleaf</artifactId>  
  86.         </dependency>  
  87.         <dependency>  
  88.             <groupId>net.sourceforge.nekohtml</groupId>  
  89.             <artifactId>nekohtml</artifactId>  
  90.             <version>1.9.22</version>  
  91.         </dependency>  
  92.   
  93.         <dependency>  
  94.             <groupId>org.springframework.boot</groupId>  
  95.             <artifactId>spring-boot-starter-test</artifactId>  
  96.             <scope>test</scope>  
  97.         </dependency>  
  98.     </dependencies>  
  99.   
  100.     <!--<dependencyManagement>-->  
  101.         <!--<dependencies>-->  
  102.             <!--<dependency>-->  
  103.                 <!--<groupId>org.springframework.cloud</groupId>-->  
  104.                 <!--<artifactId>spring-cloud-dependencies</artifactId>-->  
  105.                 <!--<version>Dalston.RC1</version>-->  
  106.                 <!--<type>pom</type>-->  
  107.                 <!--<scope>import</scope>-->  
  108.             <!--</dependency>-->  
  109.         <!--</dependencies>-->  
  110.     <!--</dependencyManagement>-->  
  111.   
  112.     <build>  
  113.         <plugins>  
  114.             <plugin>  
  115.                 <groupId>org.springframework.boot</groupId>  
  116.                 <artifactId>spring-boot-maven-plugin</artifactId>  
  117.             </plugin>  
  118.             <!-- mybatis generator 自动生成代码插件 -->  
  119.             <plugin>  
  120.                 <groupId>org.mybatis.generator</groupId>  
  121.                 <artifactId>mybatis-generator-maven-plugin</artifactId>  
  122.                 <version>${mybatis.generator.version}</version>  
  123.             </plugin>  
  124.         </plugins>  
  125.     </build>  
  126.   
  127.     <repositories>  
  128.         <repository>  
  129.             <id>spring-milestones</id>  
  130.             <name>Spring Milestones</name>  
  131.             <url>https://repo.spring.io/milestone</url>  
  132.             <snapshots>  
  133.                 <enabled>false</enabled>  
  134.             </snapshots>  
  135.         </repository>  
  136.     </repositories>  
  137.   
  138.   
  139. </project>  

3、springboot应用主入口开启缓存

[java]  view plain  copy
  1. package com.xuan;  
  2.   
  3. import org.mybatis.spring.annotation.MapperScan;  
  4. import org.springframework.boot.SpringApplication;  
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  6. import org.springframework.cache.annotation.EnableCaching;  
  7. import org.springframework.transaction.annotation.EnableTransactionManagement;  
  8.   
  9.   
  10. @SpringBootApplication  
  11. @EnableCaching //开启缓存  
  12. @EnableTransactionManagement // 开启事务管理  
  13. @MapperScan("com.xuan.mapper"// 必须加这个,不加报错,如果不加,也可以在每个mapper上添加@Mapper注释,并且这里还要多填一个注释,那个我忘了,我一直用这个注解  
  14. public class MyspringbootApplication {  
  15.   
  16.     public static void main(String[] args) {  
  17.         SpringApplication.run(MyspringbootApplication.class, args);  
  18.     }  
  19. }  

4、到这一步就可以使用redis缓存,要结合更高级的redisTemplate去使用redis还需要添加一些配置类

springboot主入口开启缓存后,可以使用redis 测试注解使用:

[java]  view plain  copy
  1. @GetMapping(value="/one/{id}")  
  2. @Cacheable(value = "getOneVideo")  
  3. public Video getOneVideo(@PathVariable Integer id){  
  4.     System.out.println("没redis缓存");  
  5.     return videoMapper.selectByPrimaryKey(id);  
  6. }  

5、增加集成redistemplate配置(读取springboot配置文件的值的时候,名称注意一一对应,否则会读取不到)

[java]  view plain  copy
  1. package com.xuan.config;  
  2.   
  3. import org.apache.log4j.Logger;  
  4. import org.springframework.beans.factory.annotation.Value;  
  5. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;  
  6. import org.springframework.boot.context.properties.ConfigurationProperties;  
  7. import org.springframework.context.annotation.Bean;  
  8. import org.springframework.context.annotation.Configuration;  
  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 redis.clients.jedis.JedisPoolConfig;  
  13.   
  14. /** 
  15.  * Created by chenqixuan on 17/10/25. 
  16.  * 集成RedisTemplate 
  17.  */  
  18. @Configuration  
  19. @EnableAutoConfiguration  
  20. public class RedisConfig {  
  21.   
  22.     private static Logger logger = Logger.getLogger(RedisConfig.class);  
  23.   
  24.     //获取springboot配置文件的值 (get的时候获取)  
  25.     @Value("${spring.redis.hostName}")  
  26.     private String host;  
  27.   
  28.     @Value("${spring.redis.password}")  
  29.     private String password;  
  30.   
  31.   
  32.     /** 
  33.      * @Bean 和 @ConfigurationProperties 
  34.      * 该功能在官方文档是没有提到的,我们可以把@ConfigurationProperties和@Bean和在一起使用。 
  35.      * 举个例子,我们需要用@Bean配置一个Config对象,Config对象有a,b,c成员变量需要配置, 
  36.      * 那么我们只要在yml或properties中定义了a=1,b=2,c=3, 
  37.      * 然后通过@ConfigurationProperties就能把值注入进Config对象中 
  38.      * @return 
  39.      */  
  40.     @Bean  
  41.     @ConfigurationProperties(prefix = "spring.redis.pool")  
  42.     public JedisPoolConfig getRedisConfig() {  
  43.         JedisPoolConfig config = new JedisPoolConfig();  
  44.         return config;  
  45.     }  
  46.   
  47.     @Bean  
  48.     @ConfigurationProperties(prefix = "spring.redis")  
  49.     public JedisConnectionFactory getConnectionFactory() {  
  50.         JedisConnectionFactory factory = new JedisConnectionFactory();  
  51.         factory.setUsePool(true);  
  52.         JedisPoolConfig config = getRedisConfig();  
  53.         factory.setPoolConfig(config);  
  54.         logger.info("JedisConnectionFactory bean init success.");  
  55.         return factory;  
  56.     }  
  57.   
  58.   
  59.     @Bean  
  60.     public RedisTemplate<?, ?> getRedisTemplate() {  
  61.         JedisConnectionFactory factory = getConnectionFactory();  
  62.         logger.info(this.host+","+factory.getHostName()+","+factory.getDatabase());  
  63.         logger.info(this.password+","+factory.getPassword());  
  64.         logger.info(factory.getPoolConfig().getMaxIdle());  
  65. //        factory.setHostName(this.host);  
  66. //        factory.setPassword(this.password);  
  67.         RedisTemplate<?, ?> template = new StringRedisTemplate(getConnectionFactory());  
  68.         return template;  
  69.     }  
  70. }  

6、基于redistemplate的工具类

[java]  view plain  copy
  1. package com.xuan.services.impl;  
  2.   
  3. import com.xuan.services.RedisService;  
  4. import com.xuan.utils.JSONUtil;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  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.data.redis.serializer.RedisSerializer;  
  11. import org.springframework.stereotype.Service;  
  12.   
  13. import javax.annotation.Resource;  
  14. import java.util.List;  
  15. import java.util.concurrent.TimeUnit;  
  16.   
  17. /** 
  18.  * Created by chenqixuan on 17/10/25. 
  19.  * 
  20.  */  
  21. @Service  
  22. public class RedisServiceImpl implements RedisService {  
  23.   
  24.   
  25.     @Resource  
  26.     private RedisTemplate<String, ?> redisTemplate;  
  27.   
  28.     @Override  
  29.     public boolean set(final String key, final String value) {  
  30.         boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
  31.             @Override  
  32.             public Boolean doInRedis(RedisConnection connection) throws DataAccessException {  
  33.                 RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
  34.                 connection.set(serializer.serialize(key), serializer.serialize(value));  
  35.                 return true;  
  36.             }  
  37.         });  
  38.         return result;  
  39.     }  
  40.   
  41.     @Override  
  42.     public String get(final String key){  
  43.         String result = redisTemplate.execute(new RedisCallback<String>() {  
  44.             @Override  
  45.             public String doInRedis(RedisConnection connection) throws DataAccessException {  
  46.                 RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
  47.                 byte[] value =  connection.get(serializer.serialize(key));  
  48.                 return serializer.deserialize(value);  
  49.             }  
  50.         });  
  51.         return result;  
  52.     }  
  53.   
  54.     @Override  
  55.     public boolean expire(final String key, long expire) {  
  56.         return redisTemplate.expire(key, expire, TimeUnit.SECONDS);  
  57.     }  
  58.   
  59.     @Override  
  60.     public <T> boolean setList(String key, List<T> list) {  
  61.         String value = JSONUtil.toJson(list);  
  62.         return set(key,value);  
  63.     }  
  64.   
  65.     @Override  
  66.     public <T> List<T> getList(String key, Class<T> clz) {  
  67.         String json = get(key);  
  68.         if(json!=null){  
  69.             List<T> list = JSONUtil.toList(json, clz);  
  70.             return list;  
  71.         }  
  72.         return null;  
  73.     }  
  74.   
  75.     @Override  
  76.     public long lpush(final String key, Object obj) {  
  77.         final String value = JSONUtil.toJson(obj);  
  78.         long result = redisTemplate.execute(new RedisCallback<Long>() {  
  79.             @Override  
  80.             public Long doInRedis(RedisConnection connection) throws DataAccessException {  
  81.                 RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
  82.                 long count = connection.lPush(serializer.serialize(key), serializer.serialize(value));  
  83.                 return count;  
  84.             }  
  85.         });  
  86.         return result;  
  87.     }  
  88.   
  89.     @Override  
  90.     public long rpush(final String key, Object obj) {  
  91.         final String value = JSONUtil.toJson(obj);  
  92.         long result = redisTemplate.execute(new RedisCallback<Long>() {  
  93.             @Override  
  94.             public Long doInRedis(RedisConnection connection) throws DataAccessException {  
  95.                 RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
  96.                 long count = connection.rPush(serializer.serialize(key), serializer.serialize(value));  
  97.                 return count;  
  98.             }  
  99.         });  
  100.         return result;  
  101.     }  
  102.   
  103.     @Override  
  104.     public String lpop(final String key) {  
  105.         String result = redisTemplate.execute(new RedisCallback<String>() {  
  106.             @Override  
  107.             public String doInRedis(RedisConnection connection) throws DataAccessException {  
  108.                 RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
  109.                 byte[] res =  connection.lPop(serializer.serialize(key));  
  110.                 return serializer.deserialize(res);  
  111.             }  
  112.         });  
  113.         return result;  
  114.     }  
  115. }  

7、Json工具类:利用了gson依赖

[html]  view plain  copy
  1. package com.xuan.utils;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import com.google.gson.Gson;  
  9. import com.google.gson.JsonArray;  
  10. import com.google.gson.JsonElement;  
  11. import com.google.gson.JsonObject;  
  12. import com.google.gson.JsonParser;  
  13. import com.google.gson.reflect.TypeToken;  
  14.   
  15. /**  
  16.  *   
  17.  * Created by chenqixuan on 17/10/25.  
  18.  * @desc json util   
  19.  */  
  20. public class JSONUtil {  
  21.       
  22.     private static Gson gson = null;   
  23.       
  24.     static{  
  25.         gson  = new Gson();//todo yyyy-MM-dd HH:mm:ss   
  26.     }  
  27.       
  28.     public static synchronized Gson newInstance(){  
  29.         if(gson == null){  
  30.             gson =  new Gson();  
  31.         }  
  32.         return gson;  
  33.     }  
  34.       
  35.     public static String toJson(Object obj){  
  36.         return gson.toJson(obj);  
  37.     }  
  38.       
  39.     public static <T> T toBean(String json,Class<T> clz){  
  40.           
  41.         return gson.fromJson(json, clz);  
  42.     }  
  43.       
  44.     public static <T> Map<String, T> toMap(String json,Class<T> clz){  
  45.          Map<String, JsonObject> map = gson.fromJson(json, new TypeToken<Map<String,JsonObject>>(){}.getType());  
  46.          Map<String, T> result = new HashMap<>();  
  47.          for(String key:map.keySet()){  
  48.              result.put(key,gson.fromJson(map.get(key),clz) );  
  49.          }  
  50.          return result;  
  51.     }  
  52.       
  53.     public static Map<String, Object> toMap(String json){  
  54.          Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String,Object>>(){}.getType());  
  55.          return map;  
  56.     }  
  57.       
  58.     public static <T> List<T> toList(String json,Class<T> clz){  
  59.         JsonArray array = new JsonParser().parse(json).getAsJsonArray();    
  60.         List<T> list  = new ArrayList<>();  
  61.         for(final JsonElement elem : array){    
  62.              list.add(gson.fromJson(elem, clz));  
  63.         }  
  64.         return list;  
  65.     }  
  66.       
  67.     public static void main(String[] args) {  
  68.     }  
  69.       
  70. }  

8、使用:

[java]  view plain  copy
  1. package com.xuan.controller;  
  2.   
  3. import com.xuan.config.RedisProperties;  
  4. import com.xuan.entity.Video;  
  5. import com.xuan.entity.VideoExample;  
  6. import com.xuan.mapper.VideoMapper;  
  7. import com.xuan.services.RedisService;  
  8. import com.xuan.services.VideoService;  
  9. import org.springframework.beans.factory.annotation.Autowired;  
  10. import org.springframework.cache.annotation.Cacheable;  
  11. import org.springframework.web.bind.annotation.GetMapping;  
  12. import org.springframework.web.bind.annotation.PathVariable;  
  13. import org.springframework.web.bind.annotation.RequestMapping;  
  14. import org.springframework.web.bind.annotation.RestController;  
  15.   
  16. import java.util.List;  
  17.   
  18. /** 
  19.  * Created by chenqixuan on 17/10/25. 
  20.  */  
  21. @RestController  
  22. @RequestMapping("/video")  
  23. public class VideoController {  
  24.   
  25.     @Autowired  
  26.     private VideoMapper videoMapper;  
  27.   
  28.     @Autowired  
  29.     private VideoService videoService;  
  30.   
  31.     @Autowired  
  32.     private RedisService redisService;  
  33.   
  34.   
  35.     @GetMapping(value="/redis/{id}")  
  36.     public List<Video> getAllVideo(@PathVariable String id){  
  37.         redisService.set(id,id);  
  38.         System.out.println(redisService.get(id));  
  39.         VideoExample example = new VideoExample();  
  40.         return videoMapper.selectByExample(example);  
  41.     }  
  42.   
  43.     @GetMapping(value="/all")  
  44.     public List<Video> getAllVideo(){  
  45.         redisService.set("key2","9999");  
  46.         VideoExample example = new VideoExample();  
  47.         return videoMapper.selectByExample(example);  
  48.     }  
  49.   
  50.     @GetMapping(value="/one/{id}")  
  51.     @Cacheable(value = "getOneVideo")  
  52.     public Video getOneVideo(@PathVariable Integer id){  
  53.         System.out.println("没redis缓存");  
  54.         return videoMapper.selectByPrimaryKey(id);  
  55.     }  
  56.   
  57.     /** 
  58.      * 事务验证 
  59.      * @return 
  60.      */  
  61.     @GetMapping(value="/add")  
  62.     public String addVideo(){  
  63.   
  64.         try {  
  65.             videoService.addVideo();  
  66.             return "Transactional YES";  
  67.         } catch (Exception e) {  
  68.             e.printStackTrace();  
  69.             return "Transactional NO";  
  70.         }  
  71.   
  72.   
  73.     }  

猜你喜欢

转载自blog.csdn.net/weixin_40584932/article/details/80651758