springboot整合redis,註解方式
之前也實現過springboot整合redis,主要介紹其原理,以及基本的實現,下面是傳送門。
這次還是spring整合redis,實現方式用到註解。
1、@Cacheable:作用是主要針對方法配置,能夠根據方法的請求引數對其結果進行快取
主要引數說明:
(1)value :
快取的名稱,在 spring 配置檔案中定義,必須指定至少一個,例如:@Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”}。
(2)key :快取的 key,可以為空,如果指定要按照 SpEL 表示式編寫,如果不指定,則預設按照方法的所有引數進行組合,例如:@Cacheable(value=”testcache”,key=”#userName”)。
(3)condition
當然還包括其他的引數,就不一一說明了。
2、@CachePut:作用是主要針對方法配置,能夠根據方法的請求引數對其結果進行快取,和 @Cacheable 不同的是,它每次都會觸發真實方法的呼叫
主要引數說明:
**(1)**value , key 和 condition 引數配置和@Cacheable一樣。
3、@CacheEvict
主要引數說明:
(1)value , key 和 condition 引數配置和@Cacheable一樣。
(2)allEntries :是否清空所有快取內容,預設為 false,如果指定為 true,則方法呼叫後將立即清空所有快取,例如:@CachEvict(value=”testcache”,allEntries=true)。
(3)beforeInvocation :是否在方法執行前就清空,預設為 false,如果指定為 true,則在方法還沒有執行的時候就清空快取,預設情況下,如果方法執行丟擲異常,則不會清空快取,例如@CachEvict(value=”testcache”,beforeInvocation=true)。
- pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kongl.web</groupId>
<artifactId>springboot-jpa-redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-jpa-redis</name>
<url>http://maven.apache.org</url>
<!-- Spring Boot 啟動父依賴 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mybatis-spring-boot>1.2.0</mybatis-spring-boot>
<mysql-connector>5.1.39</mysql-connector>
</properties>
<dependencies>
<!-- Spring Boot Web 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Redis 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!-- Spring Boot Test 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL 連線驅動依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector}</version>
</dependency>
<!-- 熱部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
<!-- Junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!--fork : 如果沒有該項配置,肯呢個devtools不會起作用,即應用不會restart -->
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
- application.properties中redis的一些配置,也可以通過程式碼實現
## Redis 配置
## Redis資料庫索引(預設為0)
spring.redis.database=0
## Redis伺服器地址
spring.redis.host=192.168.117.88
## Redis伺服器連線埠
spring.redis.port=6379
## Redis伺服器連線密碼(預設為空)
spring.redis.password=
## 連線池最大連線數(使用負值表示沒有限制)
spring.redis.pool.max-active=8
## 連線池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
## 連線池中的最大空閒連線
spring.redis.pool.max-idle=8
## 連線池中的最小空閒連線
spring.redis.pool.min-idle=0
## 連線超時時間(毫秒)
spring.redis.timeout=0
- RedisConfig.java
@Configuration
@EnableCaching//開啟註解
public class RedisConfig {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){
RedisTemplate<Object, Object> template=new RedisTemplate<Object, Object>();
template.setConnectionFactory(connectionFactory);
//實現序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
//實現序列化和反序列化redis的value值,預設使用JdkSerializationRedisSerializer
//template.setValueSerializer(new RedisObjectSerializer());
//template.setValueSerializer();
return template;
}
@Bean
public CacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
// cacheManager.setCacheNames(Arrays.asList("users", "emptyUsers"));
cacheManager.setUsePrefix(true);
// Number of seconds before expiration. Defaults to unlimited (0)
cacheManager.setDefaultExpiration(1800L);
return cacheManager;
}
//自定義keyGenerator必須實現org.springframework.cache.interceptor.KeyGenerator介面
@Bean
public KeyGenerator accountKeyGenerator() {
return new KeyGenerator(){
@Override
public Object generate(Object target, Method method, Object... params) {
//first parameter is caching object
//second paramter is the name of the method, we like the caching key has nothing to do with method name
//third parameter is the list of parameters in the method being called
return target.getClass().toString() + "accountId:" + params[0].toString();
}
};
}
}
4、service快取實現
@Cacheable(value="cat", keyGenerator = "accountKeyGenerator")
@Override
public Cat findOneCat(Integer id) {
System.out.println("開始查詢.....");
try {
Thread.sleep(3 * 1000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("查詢結束......");
Cat cat=catRepository.findOne(id);
return cat;
}
5、controller
@RequestMapping(value = "/cat/{id}", method = RequestMethod.GET)
public Cat findOne(@PathVariable("id") Integer id) {
long beginTime=System.currentTimeMillis();
Cat cat=catService.findOneCat(id);
long time=System.currentTimeMillis()-beginTime;
System.out.println(time);
return cat;
}
結果演示:http://localhost:8080/cat/1 測試快取
第一次結果:
可以看到用時3207
第二、三次結果
可以看到3207ms,之後的兩次,首先沒有執行service的方法列印資料,其次用時大大減少一次用時5ms一次用時2ms,測試完畢。
總結
本著記錄和學習的態度去完成本次整合,如果有錯誤之處請大神之處,謝謝啦。原始碼如下,本次整合了Springboot+redis+SpringJPA,所以原始碼直接執行即可,記得資料庫寫兩條資料。
springboot-redis-jpa程式碼