使用HystrixCommand 怎么能存到方法的正确返回结果 而不是存fallbackMethod的返回结果 使用自定义注解实现
时间: 2024-03-08 19:49:15 浏览: 27
您可以通过自定义注解和AOP的方式来实现此功能。首先,定义一个自定义注解,如`@CacheableResult`,用于标注需要缓存的方法。然后,使用AOP拦截被`@CacheableResult`标注的方法,在方法执行前先从缓存中查找是否有对应的结果,如果有,直接返回缓存中的结果,否则执行方法并将方法的返回结果存到缓存中。具体实现过程如下:
1. 定义自定义注解`@CacheableResult`:
```java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CacheableResult {
String value();
}
```
2. 定义缓存管理类`CacheManager`,用于管理缓存:
```java
@Component
public class CacheManager {
private static final Map<String, Object> CACHE = new ConcurrentHashMap<>();
public Object get(String key) {
return CACHE.get(key);
}
public void put(String key, Object value) {
CACHE.put(key, value);
}
}
```
3. 定义AOP切面`CacheableResultAspect`,用于拦截被`@CacheableResult`标注的方法:
```java
@Aspect
@Component
public class CacheableResultAspect {
@Autowired
private CacheManager cacheManager;
@Around("@annotation(cacheableResult)")
public Object cacheableResult(ProceedingJoinPoint joinPoint, CacheableResult cacheableResult) throws Throwable {
String key = cacheableResult.value();
Object result = cacheManager.get(key);
if (result != null) {
return result;
}
result = joinPoint.proceed();
cacheManager.put(key, result);
return result;
}
}
```
4. 在需要缓存结果的方法上添加`@CacheableResult`注解,并指定缓存的key:
```java
@Service
public class UserService {
@Autowired
private CacheManager cacheManager;
@CacheableResult("user:1")
public User getUserById(Long id) {
// 从数据库中查询用户信息
User user = userDao.getUserById(id);
return user;
}
// ...
}
```
这样,当调用`getUserById`方法时,如果缓存中已经存在id为1的用户信息,则直接返回缓存中的结果,否则执行方法并将返回结果存到缓存中。