当前位置: 首页 > article >正文

Java中的服务端点响应缓存:Spring Cache抽象

Java中的服务端点响应缓存:Spring Cache抽象

大家好,我是微赚淘客返利系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!

在Java后端服务开发中,缓存是一个重要的性能优化手段。Spring框架提供了一个强大的缓存抽象,允许开发者以统一的方式使用不同的缓存技术。本文将介绍如何在Java应用中使用Spring Cache抽象来实现服务端点的响应缓存。

响应缓存的重要性

响应缓存在服务端点中的重要性体现在以下几个方面:

  1. 减少数据库负载:通过缓存热点数据,减少对数据库的直接访问,降低数据库负载。
  2. 提高响应速度:缓存可以快速返回数据,提高服务的响应速度。
  3. 节约资源:减少计算和数据库访问,节约服务器资源。

使用Spring Cache抽象实现响应缓存

Spring Cache抽象允许开发者以声明式的方式使用缓存,而不需要关心底层的缓存实现细节。

添加Spring Cache依赖

首先,我们需要在项目的pom.xml文件中添加Spring Boot的缓存依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

配置缓存管理器

接下来,我们需要配置一个缓存管理器。Spring Boot支持多种缓存实现,如EhCache、Caffeine、Redis等。

package cn.juwatech.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;

@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("users");
    }
}

使用缓存注解

在服务端点中,我们可以使用Spring提供的缓存注解来实现响应缓存。

package cn.juwatech.service;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    
    @Cacheable(cacheNames = "users", key = "#id")
    public User getUserById(Long id) {
        // 模拟数据库查询
        return new User(id, "John Doe");
    }

    @Cacheable(cacheNames = "users")
    public List<User> getAllUsers() {
        // 模拟数据库查询
        return List.of(new User(1L, "John Doe"), new User(2L, "Jane Doe"));
    }
}

缓存失效策略

缓存数据需要在适当的时候失效,以保证数据的一致性。

package cn.juwatech.service;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    @CacheEvict(cacheNames = "users", key = "#user.id")
    public void updateUser(User user) {
        // 更新用户信息
    }

    @CacheEvict(cacheNames = "users", allEntries = true)
    public void deleteUser(Long id) {
        // 删除用户
    }
}

集成第三方缓存

Spring Cache抽象支持多种第三方缓存技术,如EhCache、Caffeine、Redis等。以下是集成Redis作为缓存的示例。

添加Redis依赖

在项目的pom.xml文件中添加Spring Boot的Redis依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置Redis缓存管理器

配置Redis缓存管理器,以使用Redis作为缓存存储。

package cn.juwatech.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

@Configuration
@EnableCaching
public class RedisCacheConfig {
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory();
    }

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        return RedisCacheManager.builder(connectionFactory).build();
    }
}

使用Redis缓存

在服务端点中,我们可以使用Redis缓存来存储和检索数据。

package cn.juwatech.service;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    @Cacheable(cacheNames = "users", key = "#id", unless = "#result == null")
    public User getUserById(Long id) {
        // 模拟数据库查询
        return new User(id, "John Doe");
    }
}

缓存的高级配置

除了基本的缓存使用外,Spring Cache抽象还支持一些高级配置,如缓存过期时间、条件缓存等。

设置缓存过期时间

可以通过配置缓存的过期时间来控制缓存数据的生命周期。

package cn.juwatech.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.interceptor.KeyGenerator;

import java.lang.reflect.Method;

@Configuration
@EnableCaching
public class CacheConfig implements CachingConfigurer {
    
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("users");
    }

    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(":");
            sb.append(((Method) target).getName());
            for (Object param : params) {
                sb.append(":");
                sb.append(param.toString());
            }
            return sb.toString();
        };
    }

    @Bean
    public CacheResolver cacheResolver() {
        return (cacheName, targetType, method, target, args) -> {
            if ("getUserById".equals(method.getName())) {
                return "users";
            }
            return null;
        };
    }
}

总结

通过上述内容,我们学习了如何在Java应用中使用Spring Cache抽象来实现服务端点的响应缓存。通过合理配置和使用Spring Cache抽象,我们可以有效地提高服务的响应速度和性能,同时减少对数据库的直接访问,降低系统负载。

本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!


http://www.kler.cn/news/306129.html

相关文章:

  • ★ C++基础篇 ★ string类的实现
  • Python实现pdf转图片、转文字、去水印
  • 房产销售系统开发:SpringBoot技术要点
  • 避免 PyCharm 将该 Python 脚本作为测试运行
  • 串口数据波形显示工具对比
  • k8s service如何实现流量转发
  • Python 课程10-单元测试
  • 基于 TDMQ for Apache Pulsar 的跨地域复制实践
  • 2024.9.14 Python与图像处理新国大EE5731课程大作业,马尔可夫随机场和二值图割,校正立体图像的深度
  • 攻击者如何在日常网络资源中隐藏恶意软件
  • rust + bevy 实现小游戏 打包成wasm放在浏览器环境运行
  • Vue3使用Websocket进行跨页面通信
  • 2024年金九银十最新版Java面试题及答案整理(持续更新)
  • 从单体到微服务:FastAPI ‘挂载’子应用程序的转变
  • AI在医学领域:医学AI的安全与隐私全面概述
  • 【iOS】ViewController的生命周期
  • Linux06(vi/vim)
  • 【Python机器学习】循环神经网络(RNN)——超参数
  • 什么是Java 语法糖?
  • ARM驱动学习之8 动态申请字符类设备号
  • sqli-labs Basic Challenge Less_1 通关指南
  • 【AI学习】陶哲轩在 2024 年第 65 届国际数学奥林匹克(IMO)的演讲:AI 与数学
  • 基于YOLOV8+Pyqt5光伏太阳能电池板目标检测系统
  • 使用docker配置wordpress
  • SQLite的入门级项目学习记录(一)
  • Kafka 消息丢失如何处理?
  • kubeadm方式安装k8s续:
  • 【Unity实战】SO反序列化正确姿势
  • 【智路】智路OS Airos Edge 2.0 Quick Start
  • 利用 FastAPI 和 Jinja2 模板引擎快速构建 Web 应用