spring-boot JSR107缓存实战

简介: 这几天在开发的项目中,考虑引入一些缓存机制。顺便又了解了一下spring-boot的缓存、以及JSR107、ehcache。并做了一些使用实例。

这几天在开发的项目中,考虑引入一些缓存机制。顺便又了解了一下spring-boot的缓存、以及JSR107、ehcache。并做了一些使用实例。

spring-boot缓存使用实例

spring-boot中引入依赖spring-boot-starter-cache,pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
/**
 * 启动类
 */
@SpringBootApplication
@EnableAutoConfiguration
@EnableCaching // 启用缓存
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

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

/**
 * restful类
 */
@RestController
public class SampleController {
    @Autowired
    private SampleServiceImpl sampleService;

    @RequestMapping("/sample/test")
    public BaseQueryParam test(BaseQueryParam dto) {
        return sampleService.testCache(dto);
    }

}

@Service
public class SampleServiceImpl {

    // 取第一个参数可以用这几种姿势#root.args[1]或#p0或#a0
    @Cacheable(value="SampleServiceImpl", key="#p0.resourceId")
    public BaseQueryParam testCache(BaseQueryParam param) {
        System.out.println("第1次访问时未缓存,打印此文本");
        return param;
    }

}

public class BaseQueryParam {
    /**
     * 资源标识。主要用来标识需要访问的资源类型
     */
    private String resourceId;

    public String getResourceId() {
        return resourceId;
    }

    public void setResourceId(String resourceId) {
        this.resourceId = resourceId;
    }

}

测试:

http://localhost:8080/sample/test?resourceId=abc

访问的时候当传入的参数resourceId一样时,第1次控制台打印“第1次访问时未缓存,打印此文本”,后面就没有打印。

生命周期:如果没检测到EhCache3,Hazelcast,Infinispan等类型,将会使用Simple类型,即使用ConcurrentHashMap进行缓存,这种类型的缓存是永久有效的。具体的使用可以参考org.springframework.cache.concurrent.ConcurrentMapCacheManager

使用JSR107和ehcache

JSR107的注解为@CacheResult,springboot建议不要和@Cacheable混合使用。同时改为使用ehcache来配置缓存,可以有效的管理内存的占用、缓存的生命周期等。

spring-boot中引入依赖spring-boot-starter-cachepom.xml中增加:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.2.1</version>
</dependency>
<dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
</dependency>
/**
 * 启动类
 */
@SpringBootApplication
@EnableAutoConfiguration
@EnableCaching // 启用缓存
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

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

/**
 * restful类
 */
@RestController
public class SampleController {
    @Autowired
    private SampleServiceImpl sampleService;

    @RequestMapping("/sample/test")
    public BaseQueryParam test(BaseQueryParam dto) {
        return sampleService.testCache(dto);
    }

}

@Service
public class SampleServiceImpl {

    // JSR107的注解为@CacheResult,springboot建议不要和@Cacheable混合使用
    @CacheResult(cacheName = "SampleServiceImpl", cacheKeyGenerator = SampleCacheKeyGenerator.class)
    public BaseQueryParam testCache(BaseQueryParam param) {
        System.out.println("第1次访问时未缓存,打印此文本");
        return param;
    }

    /**
     * 用于生成key的类
     */
    public static class SampleCacheKeyGenerator implements CacheKeyGenerator {

        @Override
        public GeneratedCacheKey generateCacheKey(CacheKeyInvocationContext<? extends Annotation> arg0) {
            BaseQueryParam param = (BaseQueryParam) (arg0.getAllParameters()[0].getValue());
            if (null == param) {
                return null;
            }
            return new SampleGeneratedCacheKey(param.getResourceId());
        }

    }

    /**
     * 缓存key类
     */
    public static class SampleGeneratedCacheKey implements GeneratedCacheKey {
        private static final long serialVersionUID = 1L;
        private final String key;

        public SampleGeneratedCacheKey(String key) {
            this.key = key;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((key == null) ? 0 : key.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            SampleGeneratedCacheKey other = (SampleGeneratedCacheKey) obj;
            if (key == null) {
                if (other.key != null)
                    return false;
            } else if (!key.equals(other.key))
                return false;
            return true;
        }

    }

}

public class BaseQueryParam implements Serializable { // ehcache缓存必须要实现Serializable接口
    /**
     * 资源标识。主要用来标识需要访问的资源类型
     */
    private String resourceId;

    public String getResourceId() {
        return resourceId;
    }

    public void setResourceId(String resourceId) {
        this.resourceId = resourceId;
    }

}

application.properties配置:

# SampleServiceImpl 对应cacheName = "SampleServiceImpl"
spring.cache.cache-names=SampleServiceImpl
spring.cache.ehcache.config=calsspath:ehcache.xml

关于JSR107

https://jcp.org/en/jsr/detail?id=107

描述(网上抄来的):JCache规范定义了一种对Java对象临时在内存中进行缓存的方法,包括对象的创建、共享访问、假脱机(spooling)、失效、各JVM的一致性等,可被用于缓存JSP内最经常读取的数据,如产品目录和价格列表。利用JCACHE,多数查询的反应时间会因为有缓存的数据而加快(内部测试表明反应时间大约快15倍)。

相关文章
|
3月前
|
负载均衡 监控 Java
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
本文详细介绍了 Spring Cloud Gateway 的核心功能与实践配置。首先讲解了网关模块的创建流程,包括依赖引入(gateway、nacos 服务发现、负载均衡)、端口与服务发现配置,以及路由规则的设置(需注意路径前缀重复与优先级 order)。接着深入解析路由断言,涵盖 After、Before、Path 等 12 种内置断言的参数、作用及配置示例,并说明了自定义断言的实现方法。随后重点阐述过滤器机制,区分路由过滤器(如 AddRequestHeader、RewritePath、RequestRateLimiter 等)与全局过滤器的作用范围与配置方式,提
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
|
4月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
786 3
|
2月前
|
监控 Cloud Native Java
Spring Boot 3.x 微服务架构实战指南
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Spring Boot 3.x与微服务架构,探索云原生、性能优化与高可用系统设计。以代码为笔,在二进制星河中谱写极客诗篇。关注我,共赴技术星辰大海!(238字)
Spring Boot 3.x 微服务架构实战指南
|
2月前
|
缓存 并行计算 监控
vLLM 性能优化实战:批处理、量化与缓存配置方案
本文深入解析vLLM高性能部署实践,揭秘如何通过continuous batching、PagedAttention与前缀缓存提升吞吐;详解批处理、量化、并发参数调优,助力实现高TPS与低延迟平衡,真正发挥vLLM生产级潜力。
561 0
vLLM 性能优化实战:批处理、量化与缓存配置方案
|
2月前
|
XML Java 测试技术
《深入理解Spring》:IoC容器核心原理与实战
Spring IoC通过控制反转与依赖注入实现对象间的解耦,由容器统一管理Bean的生命周期与依赖关系。支持XML、注解和Java配置三种方式,结合作用域、条件化配置与循环依赖处理等机制,提升应用的可维护性与可测试性,是现代Java开发的核心基石。
|
3月前
|
存储 缓存 NoSQL
Redis专题-实战篇二-商户查询缓存
本文介绍了缓存的基本概念、应用场景及实现方式,涵盖Redis缓存设计、缓存更新策略、缓存穿透问题及其解决方案。重点讲解了缓存空对象与布隆过滤器的使用,并通过代码示例演示了商铺查询的缓存优化实践。
217 1
Redis专题-实战篇二-商户查询缓存
|
3月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
619 5
|
3月前
|
存储 缓存 Java
Spring中@Cacheable、@CacheEvict以及其他缓存相关注解的实用介绍
缓存是提升应用性能的重要技术,Spring框架提供了丰富的缓存注解,如`@Cacheable`、`@CacheEvict`等,帮助开发者简化缓存管理。本文介绍了如何在Spring中配置缓存管理器,使用缓存注解优化数据访问,并探讨了缓存的最佳实践,以提升系统响应速度与可扩展性。
333 0
Spring中@Cacheable、@CacheEvict以及其他缓存相关注解的实用介绍
|
4月前
|
人工智能 监控 安全
如何快速上手【Spring AOP】?核心应用实战(上篇)
哈喽大家好吖~欢迎来到Spring AOP系列教程的上篇 - 应用篇。在本篇,我们将专注于Spring AOP的实际应用,通过具体的代码示例和场景分析,帮助大家掌握AOP的使用方法和技巧。而在后续的下篇中,我们将深入探讨Spring AOP的实现原理和底层机制。 AOP(Aspect-Oriented Programming,面向切面编程)是Spring框架中的核心特性之一,它能够帮助我们解决横切关注点(如日志记录、性能统计、安全控制、事务管理等)的问题,提高代码的模块化程度和复用性。

热门文章

最新文章