在當前互聯網環境下,緩存隨處可見,利用緩存可以很好的提升系統性能,特別是對於查詢操作,可以有效的減少數據庫壓力,Redis 是一個開源(BSD許可)的,內存中的數據結構存儲系統,它可以用作數據庫、緩存和消息中間件,Redis 的優勢包括它的速度、支持豐富的數據類型、操作原子性,以及它的通用性。SpringBoot:一款Spring框架的子框架,也可以叫微服務框架,SpringBoot充分利用了JavaConfig的配置模式以及“約定優於配置”的理念,能夠極大的簡化基於SpringMVC的Web應用和REST服務開發。本篇介紹注解方式在springboot項目中使用redis做緩存。
1、在pom.xml中引入相關依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置redisconfig,在實際項目中可以通過配置KeyGenerator來指定緩存信息的key的生成規則
package com.example.demo; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; 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; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) { RedisCacheManager rm = new RedisCacheManager(redisTemplate); rm.setDefaultExpiration(30l);// 設置緩存時間 return rm; } // @Bean // public KeyGenerator myKeyGenerator(){ // return new KeyGenerator() { // @Override // public Object generate(Object target, Method method, Object... params) { // StringBuilder sb = new StringBuilder(); // sb.append(target.getClass().getName()); // sb.append(method.getName()); // for (Object obj : params) { // sb.append(obj.toString()); // } // return sb.toString(); // } // }; // // } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); @SuppressWarnings({ "rawtypes", "unchecked" }) Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
3、創建實體類
package com.example.demo; public class User { public User() { } private int id; private String name; private int age; public User(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
4、service類,使用注解來做緩存
package com.example.demo; import java.util.Date; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class UserService { // @Cacheable緩存key為name的數據到緩存usercache中 @Cacheable(value = "usercache", key = "#p0") public User findUser(String name) { System.out.println("無緩存時執行下面代碼,獲取zhangsan,Time:" + new Date().getSeconds()); return new User(1, "zhangsan", 13);// 模擬從持久層獲取數據 } // @CacheEvict從緩存usercache中刪除key為name的數據 @CacheEvict(value = "usercache", key = "#p0") public void removeUser(String name) { System.out.println("刪除數據" + name + ",同時清除對應的緩存"); } // @CachePut緩存新增的數據到緩存usercache中 @CachePut(value = "usercache", key = "#p0") public User save(String name, int id) { System.out.println("添加lisi用戶"); return new User(2, "lisi", 13); } @Cacheable(value = "usercache", key = "#p0") public User findUser2(String name) { System.out.println("無緩存時執行下面代碼,獲取lisi,Time:" + new Date().getSeconds()); return new User(2, "lisi", 13);// 模擬從持久層獲取數據 } }
5、控制器類
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired UserService userService; @GetMapping("/finduser1") public User finduser1() { return userService.findUser("zhangsan"); } @GetMapping("/finduser2") public User finduser2() { return userService.findUser2("lisi"); } @GetMapping("/adduser2") public User adduser2() { return userService.save("lisi", 13); } @GetMapping("/delete") public void removeUser() { userService.removeUser("zhangsan"); } }
6、配置信息,這里使用docker在本地虛擬機啟動一個redis服務
spring.redis.database=0 spring.redis.host=192.168.86.133 spring.redis.password= spring.redis.port=6379 spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 spring.redis.pool.max-active=100 spring.redis.pool.max-wait=-1
啟動redis服務,然后啟動本springboot項目,通過訪問對應的url,可以看到在進行數據增刪改查的時候是有緩存的。
