一、活動微服務代碼生成
(1)使用代碼生成器生成招聘微服務代碼 tensquare_gathering
(2)拷貝到當前工程,並在父工程引入。
(3)修改Application類名稱爲GatheringApplication
(4)修改application.yml 中的端口爲9005 ,url 爲
jdbc:mysql://192.168.192.130:3306/tensquare_gathering?characterEncoding=UTF8&&useSSL=false
(5)進行瀏覽器測試
二、緩存實現
Spring Cache
Spring Cache使用方法與Spring對事務管理的配置相似。Spring Cache的核心就是對某
個方法進行緩存,其實質就是緩存該方法的返回結果,並把方法參數和結果用鍵值對的
方式存放到緩存中,當再次調用該方法使用相應的參數時,就會直接從緩存裏面取出指
定的結果進行返回
常用註解:
@Cacheable-------使用這個註解的方法在執行後會緩存其返回結果。
@CacheEvict--------使用這個註解的方法在其執行前或執行後移除Spring Cache中的某些
元素。
(1)在tensquare_gathering的pom.xml中引入SpringDataRedis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
(2)修改application.yml , 在spring節點下添加redis 配置
redis:
host: 192.168.192.130
(3)爲GatheringApplication添加@EnableCaching開啓緩存支持
@EnableCaching
(4)在GatheringService的findById方法添加緩存註解,這樣當此方法第一次運行,在
緩存中沒有找到對應的value和key,則將查詢結果放入緩存。
/**
* 根據ID查詢實體
* @param id
* @return
*/
@Cacheable(value="gathering",key="#id")
public Gathering findById(String id) {
return gatheringDao.findById(id).get();
}
(5)當我們對數據進行刪改的時候,需要更新緩存。其實更新緩存也就是清除緩存,因
爲清除緩存後,用戶再次調用查詢方法無法提取緩存會重新查找數據庫中的記錄並放入
緩存。
在GatheringService的update、deleteById方法上添加清除緩存的註解
/**
* 修改
* @param gathering
*/
@CacheEvict(value="gathering",key="#gathering.id")
public void update(Gathering gathering) {
gatheringDao.save(gathering);
}
/**
* 刪除
* @param id
*/
@CacheEvict(value="gathering",key="#id")
public void deleteById(String id) {
gatheringDao.deleteById(id);
}