springboot 使用 Cache

1.写接口:

package com.example.demo.example;

import org.springframework.cache.annotation.Cacheable;
 

/**
 * @Author lyr
 * @create 2020/2/17 16:01
 */

public interface CacheExample {
    @Cacheable(cacheNames = {"list"},key = "#id")
    String cacheList(Integer id);
}

2.写实现类:

package com.example.demo.example;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

/**
 * 注意: @Component注解要放在实现类
 *
 * @Author lyr
 * @create 2020/2/17 16:02
 */
@Component
public class Example implements CacheExample {

    private Integer data = 100;


    @CachePut(cacheNames = "data",key = "#id")
    @Override
    public String dataUpdate(Integer id) {
        this.data = data+ (int) (Math.random() * 1000);
        return this.data.toString();
    }

    @Cacheable(cacheNames = {"data"},key = "#id")
    @Override
    public String cacheList(Integer id) {
        System.out.println("执行可查询操作");
        return data.toString();
    }


}

3.调用:

package com.example.demo;

import com.example.demo.example.CacheExample;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;

@SpringBootTest
 
class DemoApplicationTests {
    @Autowired
    public CacheExample cacheExample;

    @Test
    void contextLoads() {
        String[] arr = new String[3];
        arr[0] = cacheExample.cacheList(1);
        arr[1] = cacheExample.cacheList(1);
        arr[2] = cacheExample.cacheList(1);
        System.out.println(Arrays.toString(arr));
    }

}

4.得到结果:
在这里插入图片描述
结论:没有调用 springboot的 缓存
在这里插入图片描述

再运行:

在这里插入图片描述

发布了151 篇原创文章 · 获赞 7 · 访问量 7512

猜你喜欢

转载自blog.csdn.net/qq_43923045/article/details/104360699
今日推荐