SpringBoot集成阿里缓存框架Jetcache代替Spring Cache

1. 简介

  JetCache是基于Java开发的统一API和使用简单的缓存框架,它提供的注解比Spring Cache中的注解更加强大。JetCache中的注释支持原生TTL,两级缓存和分布式自动刷新,也可以手动编写实例。目前有四个实现:RedisCache、TairCache(在Github上不是开源的)、CaffeineCache(在内存中的)和一个简单的LinkedHashMapCache(在内存中的)。
  仓库地址:https://github.com/alibaba/jetcache

2. 示例代码

  • 创建工程
  • 修改pom.xml
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.c3stones</groupId>
	<artifactId>spring-boot-jetcache-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-jetcache-demo</name>
	<description>Spring Boot Jetcache Demo</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.4.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>com.alicp.jetcache</groupId>
			<artifactId>jetcache-starter-redis</artifactId>
			<version>2.6.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
  • 创建Service
import com.c3stones.entity.Config;

/**
 * 配置Service
 * 
 * @author CL
 *
 */
public interface ConfigService {

	/**
	 * 新增配置
	 * 
	 * @param config 配置类
	 * @return
	 */
	void add(Config config);

	/**
	 * 获取配置值
	 * 
	 * @param configKey 配置键
	 * @return
	 */
	String get(String configKey);

	/**
	 * 更新配置
	 * 
	 * @param config 配置类
	 */
	void update(Config config);

	/**
	 * 删除配置
	 * 
	 * @param configKey 配置键
	 */
	void delete(String configKey);

}
  • 创建Service实现
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.alicp.jetcache.anno.CacheInvalidate;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CacheUpdate;
import com.alicp.jetcache.anno.Cached;
import com.c3stones.entity.Config;
import com.c3stones.service.ConfigService;

/**
 * 配置Service 实现
 * 
 * @author CL
 *
 */
@Service
public class ConfigServiceImpl implements ConfigService {

	private static Map<String, String> configMap = new HashMap<>();

	/**
	 * 新增配置
	 * 
	 * @param config 配置类
	 */
	@Override
	public void add(Config config) {
		System.out.println("新增配置 => " + config.getConfigKey());
		configMap.put(config.getConfigKey(), config.getConfigValue());
	}

	/**
	 * 获取配置值
	 * 
	 * @param configKey 配置键
	 * @return
	 */
	@Override
	@Cached(name = "configCache", key = "#configKey", expire = 3600, cacheType = CacheType.BOTH)
	public String get(String configKey) {
		System.out.println("获取配置值 => " + configKey);
		return configMap.get(configKey);
	}

	/**
	 * 更新配置
	 * 
	 * @param config 配置类
	 */
	@Override
	@CacheUpdate(name = "configCache", key = "#config.configKey", value = "#config.configValue")
	public void update(Config config) {
		System.out.println("更新配置 => " + config.getConfigKey());
		configMap.replace(config.getConfigKey(), config.getConfigValue());
	}

	/**
	 * 删除配置
	 * 
	 * @param configKey 配置键
	 */
	@Override
	@CacheInvalidate(name = "configCache", key = "#configKey")
	public void delete(String configKey) {
		System.out.println("删除配置 => " + configKey);
		configMap.remove(configKey);
	}

}
  • 创建启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
import com.alicp.jetcache.anno.config.EnableMethodCache;

/**
 * 启动类
 * 
 * @author CL
 *
 */
@SpringBootApplication
@EnableMethodCache(basePackages = "com.c3stones")
@EnableCreateCacheAnnotation
public class Application {

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

}
  • 创建配置文件
      在resources下创建文件application.yml。
jetcache:
  # 控制台输出统计数据,统计间隔(单位分钟),0表示不统计
  statIntervalMinutes: 1
  # 是否加入缓存key前缀
  areaInCacheName: false
  local:
    default:
      # 缓存类型。linkedhashmap、caffeine为当前支持的本地缓存类型
      type: linkedhashmap
      # Key的转换器
      keyConvertor: fastjson
      limit: 100
  remote:
    default:
      # 缓存类型。tair、redis为当前支持的远程缓存
      type: redis
      keyConvertor: fastjson
      # 采用Java序列化存储
      valueEncoder: java
      valueDecoder: java
      poolConfig:
        minIdle: 5
        maxIdle: 20
        maxTotal: 50
      host: 127.0.0.1
      port: 6379
      password: 123456

3. 测试

  • 创建单元测试类
import org.junit.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 com.c3stones.Application;
import com.c3stones.entity.Config;
import com.c3stones.service.ConfigService;

/**
 * 配置Service 测试类
 * 
 * @author CL
 *
 */
@RunWith(value = SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ConfigServiceTest {

	@Autowired
	private ConfigService configService;

	/**
	 * 测试配置Service
	 */
	@Test
	public void configTest() {
		String configKey = "KEY1";
		Config config = new Config();
		config.setConfigKey(configKey);
		config.setConfigValue("1");
		configService.add(config);

		String configVlue1 = configService.get(configKey);
		String configVlue2 = configService.get(configKey);
		String configVlue3 = configService.get(configKey);
		System.out.println(configKey + " => " + configVlue1);
		System.out.println(configKey + " => " + configVlue2);
		System.out.println(configKey + " => " + configVlue3);

		config.setConfigValue("123");
		configService.update(config);

		String configVlue4 = configService.get(configKey);
		System.out.println(configKey + " => " + configVlue4);

		configService.delete(configKey);

		String configVlue5 = configService.get(configKey);
		System.out.println(configKey + " => " + configVlue5);

		try {
			// 配置文件中配置每一分钟控制台打印统计数据
			Thread.sleep(70000);
		} catch (InterruptedException e) {
		}
	}

}
  • 运行测试方法
      控制台打印(部分):
新增配置 => KEY1
获取配置值 => KEY1
KEY1 => 1
KEY1 => 1
KEY1 => 1
更新配置 => KEY1
KEY1 => 123
删除配置 => KEY1
获取配置值 => KEY1
KEY1 => null

  一分钟后,控制台打印统计数据:

cache              |       qps|   rate|           get|           hit|          fail|        expire|avgLoadTime|maxLoadTime
-------------------+----------+-------+--------------+--------------+--------------+--------------+-----------+-----------
configCache        |      0.09| 60.00%|             5|             3|             0|             0|        0.5|          1
configCache_local  |      0.09| 60.00%|             5|             3|             0|             0|        0.0|          0
configCache_remote |      0.04|  0.00%|             2|             0|             0|             0|        0.0|          0
-------------------+----------+-------+--------------+--------------+--------------+--------------+-----------+-----------

4. 项目地址

  spring-boot-jetcache-demo

posted @ 2021-03-08 21:57  C3Stones  阅读(2662)  评论(0编辑  收藏  举报