SpringBoot 2中使用redis用作緩存

SpringBoot2.x.x版本+redis的緩存實現

前提條件:需要有redis數據庫服務,本機位置或者遠程服務器主機上

1.首先加入對應的jar包(主要的jar依賴如下):

<!--開啓 cache 緩存-->
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-cache</artifactId>
     </dependency>
     
    <!-- 使用redis作爲緩存數據區域 -->
	<dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-data-redis</artifactId>
	</dependency>
2.在application.yml文件中配置對應的redis的相關配置內容:
#配置redis
spring:
  cache:
    type: REDIS
    cache-names: redis_cache , ehcache #緩存的名字(可以不指定)
    redis:
      time-to-live: 60000  #很重要,緩存的有效時間,以便緩存的過期(單位爲毫秒)
        
  redis:
    host: 127.0.0.1 #對應redis所在的IP地址
    port: 6379 #redis數據庫對應的端口號
    database: 0 #使用第1個數據庫,一共默認有10個(0-15)
    jedis: #一些常規配置
      pool:
        max-idle: 60
        min-idle: 30
        max-wait: 60000
        max-active: 200

3.在SpringBoot的啓動類上加上@EnableCaching 註解即可

4.需要使用的緩存方法示例:

//	@Cacheable(cacheNames={"redis_cache"},key="#no") //可正常成功執行 但no參數值必須傳值否則會報異常
	@Cacheable(cacheNames={"redis_cache"},keyGenerator="defineKeyGenerator")//no參數值可以不傳,則對應的key值爲null
	public Student getStudentByNo(Integer no)
	{
		System.out.println("進入緩存方法...");
		Student stu=null;
		if(no==null)
			stu=new Student(0,"Zero","零專業","零大學");
		else
		{
			List<Student> stus=new ArrayList<>();
			Student s1=new Student(1,"One","MOne","UOne");
			Student s2=new Student(2,"Two","MTwo","UTwo");
			Student s3=new Student(3,"Three","MThree","UThree");
			stus.add(s1);
			stus.add(s2);
			stus.add(s3);
			if(no>2)
				no=2;
			stu=stus.get(no);
		}
		
		return stu;
	}

*** DefineKeyGenerator的類定義如下(有坑):

@Component
public class DefineKeyGenerator implements KeyGenerator {

	
	@Override
	public Object generate(Object target, Method method, Object... args) {
		if(args==null)
		return method.getName();
		else
		{
			StringBuilder sb=new StringBuilder();
			for(int i=0;i<args.length;i+=1)
			{
				String value=String.valueOf(args[i]);
				sb.append(value);
			}
			return sb.toString();
		}
	}

}
generate:方法的返回值決定了緩存中所對應的key的值(若需要緩存方法(getStudentByNo)的返回結果與參數值有關,建議參數值不同時該方法(generate)的返回值也不同),若是使用方法名之類的值作爲(generate)的返回值
,則會出現傳入不同的參數值,但返回的結果卻是相同(方法不再執行,而是從緩存中獲取值)
5.運行結果示例圖:

執行之前:


執行一次:


再次執行相同的方法在緩存的有效時間內,目標方法將不再被執行,而是直接從緩存中獲取相應的值。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章