使用@Cacheable注解Redis时Redis宕机或其他原因连不上继续调用原方法的解决方案

本文主要是介绍使用@Cacheable注解Redis时Redis宕机或其他原因连不上继续调用原方法的解决方案,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《使用@Cacheable注解Redis时Redis宕机或其他原因连不上继续调用原方法的解决方案》在SpringBoot应用中,我们经常使用​​@Cacheable​​注解来缓存数据,以提高应用的性能...

@Cacheable注解Redis时,Redis宕机或其他原因连不上,继续调用原方法的解决方案

在Spring Boot应用中,我们经常使用​​@Cacheable​​注解来缓存数据,以提高应用的性能。当选择Redis作为缓存存储时,如果Redis服务因某种原因不可用(如宕机、网络问题等),默认情况下,​​@Cacheable​​注解会抛出异常,导致整个请求失败。本文将探讨如何在Redis不可用时,让​​@Cacheable​​注解继续调用原方法,确保服务的可用性和稳定性。

1. 问题背景

1.1 ​​@Cacheable​​注解的基本使用

​@Cacheable​​是Spring框架提供的一个注解,用于标识一个方法的结果需要被缓存。当该方法被调用时,Spring会先检查缓存中是否存在对应的数据,如果存在,则直接返回缓存中的数据;如果不存在,则执行方法并将结果存入缓存。

1.2 Redis宕机的影响

当Redis服务宕机或网络连接出现问题时,​​@Cacheable​​注解尝试访问Redis时会抛出异常,例如​​org.springframework.data.redis.RedisConnectionFailureException​​。这会导致方法调用失败,影响用户体验和系统稳定性。

2. 解决方案

2.1 使用自定义异常处理器

可以通过自定义异常处理器来捕获Redis连接异常,并在捕获到异常时继续调用原方法。具体步骤如下:

2.1.1 创建自定义异常处理器

首先,创建一个自定义异常处理器类,用于处理Redis连接异常。

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.CacheErrorHandler;
public class CustomCacheErrorHandler implements CacheErrorHandler {
    @Override
    public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
        // 处理读取缓存时的异常
        System.out.println("Cache get error: " + exception.getMessage());
    }
    @Override
    public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
        // 处理写入缓存时的异常
        System.out.println("Cache put error: " + exception.getMessage());
    }
    @Override
    public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
        // 处理清除缓存时的异常
        System.out.println("Cache evict error: " + exception.getMessage());
    }
    @Override
    public void handleCacheClearError(RuntimeException exception, Cache cache) {
        // 处理清空缓存时的异常
        System.out.println("Cache clear error: " + exception.getMessage());
    }
}

2.1.2 配置自定义异常处理器

在Spring Boot配置文件中,配置自定义的异常处理器。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.cache.annotation.EnableCaching;
@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public CustomCacheErrorHandler customCacheErrorHandler() {
        return new CustomCacheErrorHandler();
    }
}

2.2 使用​​@Cacheable​​的​​unless​​属性

​@Cacheable​​注解提供了一个​​unless​​属性,可以在缓存操作成功后决定是否将结果存入缓存。虽然这个属性不能直接解决Redis宕机的问题,但可以结合其他逻辑来实现类似的效果。

2.3 使用​​@Cacheable​的​​cache-null-values​​属性

设置​​@Cacheable​​注解的​​cache-null-values​​属性为​​false​​,这样即使Redis不可用,也不会将​​null​​值存入缓存。

@Cacheable(value = "myCache", cacheNullValues = false)
public User getUserById(Long id) {
    return userRepository.findById(id).orElse(null);
}

2.4 使用降级策略

在Redis不可用时,可以采用降级策略,例如从数据库中直接获取数据。这可以通过自定义的缓存管理器来实现。

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
javascriptimport Java.util.Optional;
@Configuration
public class CustomCacheManager {
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("myCache") {
            @Override
            public Cache getCache(String name) {
                Cache cache = super.getCache(name);
                if (cache == null) {
                    // 如果Redis不可用,使用本地缓存
                    cache = new ConcurrentMapCache(name);
                }
     php           return cache;
            }
        };
    }
}

我们可以在Redis不可用时,确保​​@Cacheable​​​注解继续调用原方法,从而提高系统的稳定性和可用性。具体实现方式包括自定义异常处理器、使用​​unless​​​和​​cache-null-values​​属性、以及降级策略。在使用Spring框架结合Redis实现缓存功能时,如果Redis宕机或由于其他原因导致连接不上Redis,可以通过配置​​CacheManager​​来实现当缓存不可用时自动回退到原始方法的调用。这样可以保证系统的可用性和稳定性。

以下是一个具体的实现示例:

添加依赖:首先确保你的项目中已经添加了Spring Boot和Redis的相关依赖。

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

配置Redis连接:在application.properties中配置Redis连接信息。

spring.redis.host=localhost
spring.redis.port=6379

自定义CacheManager:创建一个自定义的CacheManager,在其中处理Redis不可用的情况。

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2jsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1)) // 设置默认过期时间
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
        cacheConfigurations.put("myCache", config);
        return new FallbackRedisCacheManager(redisConnectionFactowww.chinasem.cnry, config, cacheConfigurations);
    }
}

实现FallbackRedisCacheManager:创建一个自定义的CacheManager,在Redis不可用时回退到内存缓存。

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFailureException;
import java.util.Arrays;
import java.util.List;
public class FallbackRedisCacheManager extends RedisCacheManager {
    private final CacheManager fallbackCacheManager;
    public FallbackRedisCacheManager(RedisConnectionFactory connectionFactory, RedisCacheConfiguration defaultCacheConfiguration, Map<String, RedisCacheConfiguration> initialCacheConfigurations) {
        super(connectionFactory, defaultCacheConfiguration, initialCacheConfigurations);
        SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
        simpleCacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("fallbackCache")));
        simpleCacheManager.afterPropertiesSet();
        this.fallbackCacheManager = simpleCacheManager;
    }
    @Override
    public Cache getCache(String name) {
        try {
            return super.getCache(name);
        } catch (RedisConnectionFailureException e) {
            return fallbackCacheManager.getCache(name);
        }
    }
}

使用@Cacheable注解:在需要缓存的方法上使用@Cacheable注解。

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class MyService {
    @Cacheable(value = "myCache", key = "#id")
    public String getData(String id) {
        // 模拟数据获取过程
        System.out.println("Fetching data from database for ID: " + id);
        return "Data for ID: " + id;
    }
}

通过上述配置,当Redis不可用时,​​FallbackRedisCacheManager​​会捕获到​​RedisConnectionFailureException​​异常,并回退到内存缓存。这样可以确保即使Redis宕机,系统仍然能够正常运行并返回数据。在使用Spring Cache与Redis结合时,如果Redis出现宕机或连接问题,可以通过配置​​CacheManager​​和实现自定义的​​CacheErrorHandler​​来确保即使缓存不可用,业务逻辑也能正常运行。以下是一个详细的解决方案示例:

1. 添加依赖

首先,确保你的项目中已经添加了Spring Boot Starter Cache和Spring Boot Starter Data Redis的依赖:

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

2. 配置RedisTemplate

配置​​RedisTemplate​​以使用JSON序列化方式存储对象:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new StrinlbDIaQEBEgRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

3. 配置CacheManager

配置​​CacheManager​​以使用Redis作为缓存存储:

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import java.time.Duration;
@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(60)) // 设置缓存过期时间为60分钟
                .disableCachingNullValues();
        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .build();
    }
}

4. 实现自定义的CacheErrorHandler

实现自定义的​​CacheErrorHandler​​,以便在缓存操作失败时进行处理:

import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueException;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.CacheErrorHandler;
@Configuration
public class CacheConfig extends CachingConfigurerSupport {
    @Override
    public CacheErrorHandler errorHandler() {
        return new CacheErrorHandler() {
            @Override
            public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
                // 处理缓存读取错误
                System.out.println("Cache get error: " + exception.getMessage());
            }
            @Override
            public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
                // 处理缓存写入错误
                System.out.println("Cache put error: " + exception.getMessage());
            }
            @Override
            public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
                // 处理缓存删除错误
                System.out.println("Cache evict error: " + exception.getMessage());
            }
            @Override
            public void handleCacheClearError(RuntimeException exception, Cache cache) {
                // 处理缓存清除错误
                System.out.println("Cache clear error: " + exception.getMessage());
            }
        };
    }
}

5. 使用@Cacheable注解

在需要缓存的方法上使用​​@Cacheable​​注解:

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
    @Cacheable(value = "users", key = "#userId")
    public User getUserById(String userId) {
        // 模拟从数据库获取用户信息
        System.out.println("Fetching user from database: " + userId);
        return new User(userId, "John Doe");
    }
}

6. 测试

你可以通过模拟Redis宕机或断开连接来测试上述配置是否生效。例如,可以临时关闭Redis服务,然后调用​​getUserById​​方法,查看是否能够正常返回数据。

总结

通过以上配置,当Redis不可用时,​​CacheErrorHandler​​会捕获到缓存操作的异常,并打印错误信息。同时,由于​​@Cacheable​​注解的默认行为是当缓存不可用时直接调用原方法,因此业务逻辑不会受到影响。这样可以确保系统的高可用性和稳定性。

到此这篇关于使用@Cacheable注解Redis时Redis宕机或其他原因连不上继续调用原方法的解决方案的文章就介绍到这了,更多相关@Cacheable注解 Redis宕机内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于使用@Cacheable注解Redis时Redis宕机或其他原因连不上继续调用原方法的解决方案的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154725

相关文章

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏

Redis 的 SUBSCRIBE命令详解

《Redis的SUBSCRIBE命令详解》Redis的SUBSCRIBE命令用于订阅一个或多个频道,以便接收发送到这些频道的消息,本文给大家介绍Redis的SUBSCRIBE命令,感兴趣的朋友跟随... 目录基本语法工作原理示例消息格式相关命令python 示例Redis 的 SUBSCRIBE 命令用于订

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC