JetCache快速入门小案例

本文是基于SpringBoot的小案例,废话不多说,直接上代码:
pom依赖:

<dependency>
			<groupId>com.alicp.jetcache</groupId>
			<artifactId>jetcache-starter-redis</artifactId>
			<version>2.5.12</version>
</dependency>

JetCache配置参数:格式缩进需要注意

# jetcache缓存全局配置
jetcache:
  statIntervalMinutes: 15
  areaInCacheName: false
  local:
    default:
      type: linkedhashmap
      keyConvertor: fastjson
    otherCacheName:
      type: xxx
      keyConverter: yyy
  remote:
    default:
      type: redis
      keyConvertor: fastjson
      valueEncoder: java
      valueDecoder: java
      poolConfig:
        minIdle: 5
        maxIdle: 20
        maxTotal: 50
      host: 127.0.0.1
      port: 6379

下面是通过@CreateCache注解创建一个二级缓存实例,@CreateCache注解一般用在变量上:redis分布式锁这部分请参考我之前的博客地址redis分布式锁

package com.daling.cache;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.CacheGetResult;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CreateCache;
import com.daling.bean.Student;
import com.daling.util.lock.LockUtils;
import com.daling.util.lock.jedisLock.RdLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class GatewayCache {

    private Logger logger = LoggerFactory.getLogger(GatewayCache.class);

    private final String GATEWAY_PREFIX = "gateway_";
    
    /**
     * 通过@CreateCache注解创建一个二级(内存 + 远程)缓存实例,默认超时时间是60秒,内存中的元素个数限制在50个
     */
    @CreateCache(name = GATEWAY_PREFIX, expire = 60, cacheType = CacheType.BOTH, localLimit = 50)
    private Cache<String, Student> studentCache;

    public Student getStudent() {
        Student student = new Student();
        CacheGetResult<Student> result = studentCache.GET("10000");
        if(result.isSuccess()){
            student = result.getValue();
            return student;
        }
        // 先获取锁,串行操作
        // RdLock实现了Closeable接口,try代码块结束后会执行close方法
        try(RdLock rdLock = LockUtils.getRLock(GATEWAY_PREFIX + "getStudent")){
            boolean lock = rdLock.tryLock();
            if (!lock) {
                System.out.println("获取锁过于频繁");
                return null;
            }else {
                student = new Student(100, "tanhq", 1);
                studentCache.put("10000", student);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return student;
    }
}

Student实体类,该实体类必须实现Serializable,不然无法序列化存入JetCache缓存中:

package com.daling.bean;

import java.io.Serializable;

public class Student implements Serializable {

    private Integer id;
    private String name;
    private Integer gender;
    
	//set,get方法和构造方法省略
}	

Application启动类:

package com.daling;

import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
import com.alicp.jetcache.anno.config.EnableMethodCache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;

@ComponentScan
@SpringBootApplication
//@ImportResource是引入spring配置文件.xml; @Import注解是引入带有@Configuration的java类。
@ImportResource(locations = "classpath:applicationContext.xml")
//制定开启缓存对应的包路径名,激活Cached注解
@EnableMethodCache(basePackages = "com.daling.cache")
//开启对应的CreateCache注解
@EnableCreateCacheAnnotation
public class SpringbootApplication {

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

最后一个是测试Controller:

package com.daling.controller;

import com.daling.cache.GatewayCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @RestController = @Controller + @ResponseBody
 */
@RestController
@RequestMapping(path = "/jetcache")
public class JetCacheController {

    @Autowired
    private GatewayCache gatewayCache;

    @RequestMapping(value="/getStudent")
    public void get(){
        for (int i = 0; i < 10 ; i++) {
            new Thread(() -> gatewayCache.getStudent()).start();
        }
    }
}

启动Application启动类,调用上面Controller接口地址http://localhost:8080/jetcache/getStudent即可。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JetCache 是一个基于 Java 的开源缓存库,它提供了对方法级缓存的支持。使用 JetCache 可以方便地将方法的结果缓存起来,提高应用程序的性能和响应速度。 下面是使用 JetCache 的基本步骤: 1. 添加 JetCache 依赖:将 JetCache 的依赖项添加到项目的构建文件中(如 Maven 或 Gradle)。 2. 配置缓存:在应用程序的配置文件中,配置需要使用的缓存类型和相关属性。例如,可以配置内存缓存、Redis 缓存等。 3. 注解方法:在需要进行缓存的方法上添加 JetCache 的注解,如 `@Cached`、`@CacheRemove` 等。这些注解可以指定缓存的 key、过期时间、条件等。 4. 使用缓存:在调用被注解的方法时,JetCache 会根据注解的配置自动处理缓存。如果缓存中存在所需数据,则直接返回缓存数据;否则,执行方法并将结果放入缓存。 下面是一个简单的示例: ```java import io.github.jiashunx.cache.Cache; import io.github.jiashunx.cache.annotation.Cached; public class MyService { private Cache<String, String> cache; // 构造函数或依赖注入注入 Cache 实例 @Cached(name = "myCache", key = "#param", expire = 600) public String getData(String param) { // 从数据库或其他数据源中获取数据 // ... return data; } } ``` 在上述示例中,`MyService` 使用了 JetCache 的 `@Cached` 注解对 `getData` 方法进行了缓存配置。缓存的名称为 "myCache",缓存的 key 使用方法参数 `param`,缓存的过期时间为 600 秒。当调用 `getData` 方法时,JetCache 会自动处理缓存逻辑,如果缓存中存在对应的数据,则直接返回缓存数据;否则,执行方法并将结果放入缓存。 这只是 JetCache 的基本用法,JetCache 还提供了其他更复杂的缓存策略和配置选项,可以根据具体需求进行配置和使用。 希望这个回答对您有帮助!如有更多问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值