JetCache快速入门小案例

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


			com.alicp.jetcache
			jetcache-starter-redis
			2.5.12

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 studentCache;

    public Student getStudent() {
        Student student = new Student();
        CacheGetResult 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即可。

你可能感兴趣的:(Java基础)