Caffeine Cache 简单示例

Caffeine Cache 简单示例 如下

POM依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


    <modelVersion>4.0.0</modelVersion>
    <artifactId>caffeine-cache</artifactId>
    <groupId>com.cache</groupId>
    <version>1.8-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>caffeine-cache</name>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring-boot.version>2.0.4.RELEASE</spring-boot.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>${spring-boot.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.8.6</version>
        </dependency>

    </dependencies>

</project>

启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = {"com.caffeine.cache"})
public class MainApp {

    public static void main(String[] args) {
        SpringApplication.run(MainApp.class, args);
    }
}

基础服务

public interface IBaseService {
    String queryService(Integer id);
}
import org.springframework.stereotype.Service;
import java.util.Random;

@Service
public class BaseServiceImpl implements IBaseService {

    private Random random = new Random();

    @Override
    public String queryService(Integer id) {
        //这里可以先取redis缓存再查数据库
        return String.format("%s->%s",id,(random.nextInt(100) + 1));
    }
}

缓存服务

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.RemovalCause;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

@Configuration
public class CacheConfig {

    @Autowired(required = false)
    private IBaseService baseService;

    /**
     * Cache.stats() 方法返回提供统计信息的CacheStats,如:
     * hitRate():返回命中与请求的比率
     * hitCount(): 返回命中缓存的总数
     * evictionCount():缓存逐出的数量
     * averageLoadPenalty():加载新值所花费的平均时间
     */
     @Bean("mycache1")
     public LoadingCache<Integer, String> studentCache() {
           return Caffeine.newBuilder()
                   .initialCapacity(1)//初始缓存长度为1
                   .maximumSize(10)  //最大长度为10
                   .recordStats()     //可以打开统计信息收集
                   .expireAfterWrite(1, TimeUnit.MINUTES)//设置缓存策略在1小时未写入过期缓存
                   .removalListener((Integer key, String value, RemovalCause cause) ->{
                       System.out.printf("移除缓存Key:%s  Value:%s 移除类型:%s %n", key, value ,cause);
                   })
                   .build(new CacheLoader<Integer, String>() {
               @Override
               public String load(Integer key) throws Exception {
                   String value = baseService.queryService(key);
                   return value;
               }
           });
    }

}
public interface ICacheService {

    String queryById(Integer id);

    void putCache(Integer key,String value);

    void removeCache(Integer key);

    void removeAllCache();
}

Controller测试调用

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Random;

@Controller
@ResponseBody
public class TestController {

    @Autowired
    private ICacheService myService1;

    private Random random = new Random();

    @RequestMapping(value ="/hello", method = RequestMethod.GET)
    @ResponseBody
    public String hello1() throws InterruptedException {
        int id = random.nextInt(30) + 1;
        String value = myService1.queryById(id);
        return "Hello World!"+" : ["+id+" - "+value+"]";
    }
}

 

示例较为简单,仅供参考;

Caffeine是一个基于Java的高性能缓存库,可以轻松地将缓存集成到应用程序中。以下是一个简单Caffeine使用示例: 1. 添加Caffeine依赖 在Maven项目中,可以通过在pom.xml文件中添加以下依赖来使用Caffeine: ``` <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>2.8.0</version> </dependency> ``` 2. 创建缓存对象 可以使用Caffeine的`Caffeine.newBuilder()`方法创建一个缓存对象。在创建缓存对象时,可以设置缓存的大小,过期策略等属性。例如: ``` Cache<String, String> cache = Caffeine.newBuilder() .maximumSize(1000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(); ``` 上面的代码创建了一个最大大小为1000的缓存对象,缓存中的条目将在10分钟后过期。 3. 向缓存中添加数据 可以使用`put`方法向缓存中添加数据。例如: ``` cache.put("key1", "value1"); cache.put("key2", "value2"); ``` 上面的代码向缓存中添加了两个键值对。 4. 从缓存中获取数据 可以使用`get`方法从缓存中获取数据。例如: ``` String value1 = cache.getIfPresent("key1"); String value2 = cache.getIfPresent("key2"); ``` 上面的代码从缓存中获取了两个键对应的值。 5. 删除缓存中的数据 可以使用`invalidate`方法从缓存中删除数据。例如: ``` cache.invalidate("key1"); ``` 上面的代码从缓存中删除了键为`key1`的数据。 以上就是一个简单Caffeine使用示例。通过使用Caffeine,可以轻松地将缓存集成到应用程序中,提高应用程序的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值