SpringBoot緩存之redis--最簡單的使用方式


第一步:配置redis

  這里使用的是yml類型的配置文件

 1 mybatis:
 2   mapper-locations: classpath:mapping/*.xml
 3 spring:
 4   datasource:
 5     name: miaosha
 6     url: jdbc:mysql://127.0.0.1:3306/miaosha?serverTimezone=UTC
 7     username: root
 8     password: 1234
 9     type: com.alibaba.druid.pool.DruidDataSource #數據源
10     driverClassName: com.mysql.jdbc.Driver
11   redis:
12     host: 10.0.75.1 #地址
13     port: 6379 #端口號
14     timeout: 20000 #連接超時時間
15   cache: #緩存類型
16     type: redis

 

第二步:在啟動類上添加 @EnableCaching 注解

 1 @SpringBootApplication(scanBasePackages = {"com.miaoshaproject"})
 2 @MapperScan("com.miaoshaproject.dao")
 3 @EnableCaching
 4 public class App {
 5 
 6     public static void main( String[] args ) {
 7         ConfigurableApplicationContext run = SpringApplication.run(App.class, args);
 8     }
 9 }

第三步:在需要緩存的方法上添加 @Cacheable 注解

@Service
@CacheConfig(cacheNames = {"itemService"})
public class ItemServiceImpl implements ItemService {

    @Override
    @Cacheable(value = {"item"},key ="#p0")
    public String getItemById(Integer id) {
        String name = "123";
       return name;
    }
}        

注:關於springboot緩存名的說明:

  使用SpringBoot緩存必須配置名字可以使用@CacheConfig(cacheNames = {"itemService"})在類上配置該類公用的名字,也可以使用@Cacheable(value=”item”)在方法上配置只適用於該方法的名字。如果類和方法上都有配置,以方法上的為准。

  springBoot會自動拼裝緩存名,規則是:配置的名字+兩個冒號+方法的實參;

注:關於@CacheConfig和@Cacheable注解的說明:

  @Cacheable(value=”item”),這個注釋的意思是,當調用這個方法的時候,會從一個名叫 item 的緩存中查詢,如果沒有,則執行實際的方法(即查詢數據庫),並將執行的結果存入緩存中,否則返回緩存中的對象。
  在上面代碼示例中@Cacheable注解設置了兩個參數一個是value,一個是key。key的值"#p0"在執行過程中會被getItemById方法的實參所替換,例如id的值3 那么緩存的名字就會是"item::3";如果不設置key,系統會自動也會是這個效果。

  

 

  如果是無參方法:

  @CacheConfig is a class-level annotation that allows to share the cache names,如果你在你的方法寫別的名字,那么依然以方法的名字為准。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM