SpringBoot + Redis緩存實現
1、緩存對象必須實現序列化
如:
package com.jachin.sell.VO;
/**
* @description: http請求返回的最外層對象
* @Author: JachinDo
* @Date: 2019/07/17 22:32
*/
@Data
public class ResultVO<T> implements Serializable {
// 利用插件保證序列化時唯一id
private static final long serialVersionUID = -1712970983658219564L;
// 錯誤碼
private Integer code;
// 提示信息
private String msg;
// 返回的具體內容
private T data;
}
其中18行使用插件生成唯一id:
使用方法:
快捷鍵==command+o
==:
2、緩存配置
引入如下依賴時,Spring Boot就會自動配置相關的bean:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
yml配置文件:
有密碼的話還需要配置密碼
啓動類加@EnableCaching
註解:
package com.jachin.sell;
@SpringBootApplication
@EnableCaching
public class SellApplication {
public static void main(String[] args) {
SpringApplication.run(SellApplication.class, args);
}
}
3、緩存使用舉例
必要代碼塊截取:
package com.jachin.sell.service.impl;
@Service
@CacheConfig(cacheNames = "product")
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductInfoDao dao;
@Override
@Cacheable(key = "123")
public ProductInfo findById(String productId) {
return dao.findById(productId).get();
}
@Override
@CachePut(key = "123")
public ProductInfo save(ProductInfo productInfo) {
return dao.save(productInfo);
}
}
}
@Cacheable:第一次進入會執行其標註的方法,執行後,將返回值類型的數據進行緩存,之後則不會執行方法,直接從緩存中獲取數據。
@CachePut:每一次都會執行其標註的方法,每一次都將執行後的新返回值用於更新緩存。
注意:上述兩個註解標註的方法的返回值必須相同纔行。
@CacheEvict:主要是爲了移除緩存中對應的鍵值對,主要對於那些刪除的操作,在方法執行完成後移除對應的緩存。
@CacheConfig:用來配置一些作用域相關的東西,簡化上述註解中相同屬性的編寫。
key:key值必須要寫,cacheNames + key 唯一標示緩存,而key默認值是函數入參,所以防止不統一,建議必須給出該屬性值。
更豐富的語法:
@GetMapping("/list") @Cacheable(cacheNames = "product", key = "#sellerId", condition = "#sellerId.length() > 3", unless = "#result.getCode() != 0") public ResultVO list(@RequestParam(value = "sellerId", required = false) String sellerId) {}
用到了spel表達式。condition和unless都表示緩存條件,滿足才緩存。
注意:三個緩存註解是將方法的==“返回值”==作爲value存入redis,所以,通常註解不加在Controller層的方法上,因爲Controller層的方法通常返回ModelAndView,通常加在Service層。總之,我們通常是要緩存自己定義的數據對象吧。