天天看點

Spring Boot使用redis做資料緩存 1 添加redis支援 2 redis配置 3 redis伺服器配置 4 應用 5 檢驗

1 添加redis支援

在pom.xml中添加

Xml代碼  

Spring Boot使用redis做資料緩存 1 添加redis支援 2 redis配置 3 redis伺服器配置 4 應用 5 檢驗
  1. <dependency>  
  2.    <groupId>org.springframework.boot</groupId>  
  3.    <artifactId>spring-boot-starter-redis</artifactId>  
  4. </dependency>  

2 redis配置

Java代碼  

Spring Boot使用redis做資料緩存 1 添加redis支援 2 redis配置 3 redis伺服器配置 4 應用 5 檢驗
  1. package com.wisely.ij.config;  
  2. import java.lang.reflect.Method;
  3. import org.springframework.cache.CacheManager;
  4. import org.springframework.cache.annotation.CachingConfigurerSupport;

    import org.springframework.cache.annotation.EnableCaching;

    import org.springframework.cache.interceptor.KeyGenerator;

    import org.springframework.context.annotation.Bean;

    import org.springframework.context.annotation.Configuration;

    import org.springframework.data.redis.cache.RedisCacheManager;

    import org.springframework.data.redis.connection.RedisConnectionFactory;

    import org.springframework.data.redis.core.RedisTemplate;

    import org.springframework.data.redis.core.StringRedisTemplate;

    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

  5. import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
  6. import com.fasterxml.jackson.annotation.PropertyAccessor;
  7. import com.fasterxml.jackson.databind.ObjectMapper;

    import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;

  8. @Configuration  
  9. @EnableCaching  
  10. public class RedisConfig extends CachingConfigurerSupport{  
  11.     @Bean  
  12.     public KeyGenerator wiselyKeyGenerator(){  
  13.         return new KeyGenerator() {  
  14.             @Override  
  15.             public Object generate(Object target, Method method, Object... params) {  
  16.                 StringBuilder sb = new StringBuilder();  
  17.                 sb.append(target.getClass().getName());  
  18.                 sb.append(method.getName());  
  19.                 for (Object obj : params) {  
  20.                     sb.append(obj.toString());  
  21.                 }  
  22.                 return sb.toString();  
  23.             }  
  24.         };  
  25.     }  
  26.     @Bean  
  27.     public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {  
  28.         return new RedisCacheManager(redisTemplate);  
  29.     }  
  30.     @Bean  
  31.     public RedisTemplate<String, String> redisTemplate(  
  32.             RedisConnectionFactory factory) {  
  33.         StringRedisTemplate template = new StringRedisTemplate(factory);  
  34.         Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);  
  35.         ObjectMapper om = new ObjectMapper();  
  36.         om.setVisibility(PropertyAccessor.ALL, Visibility.ANY);  
  37.         om.enableDefaultTyping(DefaultTyping.NON_FINAL);  
  38.         jackson2JsonRedisSerializer.setObjectMapper(om);  
  39.         template.setValueSerializer(jackson2JsonRedisSerializer);  
  40.         template.afterPropertiesSet();  
  41.         return template;  
  42.     }  
  43. }  

3 redis伺服器配置

Properties代碼  

Spring Boot使用redis做資料緩存 1 添加redis支援 2 redis配置 3 redis伺服器配置 4 應用 5 檢驗
  1. # REDIS (RedisProperties)  
  2. spring.redis.database=0 # database name  
  3. spring.redis.host=localhost # server host  
  4. spring.redis.password= # server password  
  5. spring.redis.port=6379 # connection port  
  6. spring.redis.pool.max-idle=10 # pool settings ...  
  7. spring.redis.pool.min-idle=0  
  8. spring.redis.pool.max-active=10  
  9. spring.redis.pool.max-wait=-1 

4 應用

測試兩個實體類

Java代碼  

Spring Boot使用redis做資料緩存 1 添加redis支援 2 redis配置 3 redis伺服器配置 4 應用 5 檢驗
  1. package com.wisely.ij.domain;  
  2. public class Address {  
  3.     private Long id;  
  4.     private String province;  
  5.     private String city;  
  6.     public Address(Long id,String province, String city) {  
  7.         this.id = id;  
  8.         this.province = province;  
  9.         this.city = city;  
  10.     }  
  11.     public Address() {  
  12.     }  
  13.     public Long getId() {  
  14.         return id;  
  15.     }  
  16.     public void setId(Long id) {  
  17.         this.id = id;  
  18.     }  
  19.     public String getProvince() {  
  20.         return province;  
  21.     }  
  22.     public void setProvince(String province) {  
  23.         this.province = province;  
  24.     }  
  25.     public String getCity() {  
  26.         return city;  
  27.     }  
  28.     public void setCity(String city) {  
  29.         this.city = city;  
  30.     }  
  31. }  

Java代碼  

Spring Boot使用redis做資料緩存 1 添加redis支援 2 redis配置 3 redis伺服器配置 4 應用 5 檢驗
  1. package com.wisely.ij.domain;  
  2. public class User {  
  3.     private Long id;  
  4.     private String firstName;  
  5.     private String lastName;  
  6.     public User(Long id,String firstName, String lastName) {  
  7.         this.id = id ;  
  8.         this.firstName = firstName;  
  9.         this.lastName = lastName;  
  10.     }  
  11.     public User() {  
  12.     }  
  13.     public Long getId() {  
  14.         return id;  
  15.     }  
  16.     public void setId(Long id) {  
  17.         this.id = id;  
  18.     }  
  19.     public String getFirstName() {  
  20.         return firstName;  
  21.     }  
  22.     public void setFirstName(String firstName) {  
  23.         this.firstName = firstName;  
  24.     }  
  25.     public String getLastName() {  
  26.         return lastName;  
  27.     }  
  28.     public void setLastName(String lastName) {  
  29.         this.lastName = lastName;  
  30.     }  
  31. }  

 使用示範

Java代碼  

Spring Boot使用redis做資料緩存 1 添加redis支援 2 redis配置 3 redis伺服器配置 4 應用 5 檢驗
  1. package com.wisely.ij.service;  
  2. import com.wisely.ij.domain.Address;  
  3. import com.wisely.ij.domain.User;  
  4. import org.springframework.cache.annotation.Cacheable;  
  5. import org.springframework.stereotype.Service;  
  6. @Service  
  7. public class DemoService {  
  8.     @Cacheable(value = "usercache", key = "#id + '_' + #firstName + '_' + #lastName") 
  9.     public User findUser(Long id,String firstName,String lastName){  
  10.         System.out.println("無緩存的時候調用這裡。");  
  11.         return new User(id,firstName,lastName);  
  12.     }  
  13.     @Cacheable(value = "addresscache", key = "#id + '_' + #province + '_' + #city")
  14.     public Address findAddress(Long id,String province,String city){  
  15.         System.out.println("無緩存的時候調用這裡。");  
  16.         return new Address(id,province,city);  
  17.     }  
  18. }  

Java代碼  

Spring Boot使用redis做資料緩存 1 添加redis支援 2 redis配置 3 redis伺服器配置 4 應用 5 檢驗
  1. package com.wisely.ij.web;  
  2. import com.wisely.ij.domain.Address;  
  3. import com.wisely.ij.domain.User;  
  4. import com.wisely.ij.service.DemoService;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.web.bind.annotation.RequestMapping;  
  8. import org.springframework.web.bind.annotation.ResponseBody;  
  9. @RestController
  10. public class DemoEndpoint{  
  11.     @Autowired  
  12.     DemoService demoService;  
  13.     @RequestMapping(value = "/test", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)   
  14.     public String putCache(){  
  15.         demoService.findUser(1L, "zhang", "san");
  16.         demoService.findAddress(2L, "jx", "gz");
  17.         System.out.println("if it not print '無緩存的時候調用。' ,it means the test is success.");
  18.         return "OK";
  19.     }  
  20.     @RequestMapping(value = "/test2", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)  
  21.     public String testCache(){  
  22.         User user = demoService.findUser(1L, "zhang", "san");  
  23.         Address address =demoService.findAddress(2L, "jx", "gz");  
  24.         System.out.println("it not excute query");  
  25.         System.out.println("user:"+"/"+user.getFirstName()+"/"+user.getLastName());  
  26.         System.out.println("address:"+"/"+address.getProvince()+"/"+address.getCity());  
  27.         return "OK";  
  28.     }  
  29. }  

5 檢驗

先通路http://localhost:8080/test 儲存緩存

Spring Boot使用redis做資料緩存 1 添加redis支援 2 redis配置 3 redis伺服器配置 4 應用 5 檢驗

再通路http://localhost:8080/test2 調用緩存裡的資料

Spring Boot使用redis做資料緩存 1 添加redis支援 2 redis配置 3 redis伺服器配置 4 應用 5 檢驗

繼續閱讀