优雅实现API接口开关:让你的应用更可控

开发 前端
通过定义AOP切面和切入点,我们可以精确地拦截需要控制的方法,并在通知中根据开关状态执行相应的逻辑。这种技术手段有助于提高代码的可维护性和可扩展性,同时提供更好的灵活性和控制性来管理接口的行为​。

环境:SpringBoot2.7.12

1. 概述

本文将介绍如何为API接口动态添加开关功能。通过这个功能,我们可以控制API接口的正常访问或显示提示信息。这有助于在开发和维护过程中更好地管理和控制API接口的行为。通过使用开关功能,我们可以轻松地在不同情况下调整接口的行为,提高系统的灵活性和可维护性。

为什么要给API接口添加开关功能呢?从以下几方面考虑:

  1. 灵活性和可扩展性:我们可以根据需要动态地控制API接口的行为。这使得在面对不同场景和需求时,可以更加灵活地调整接口的行为,而无需对代码进行修改。
  2. 安全性和控制:有时,我们可能不希望在特定情况下API接口被正常访问,例如在测试、维护或敏感数据访问等场景下。通过关闭开关并显示提示信息,我们可以对用户进行必要的通知和引导,确保接口不被未经授权的访问。
  3. 错误处理和日志记录:当API接口出现错误或异常时,关闭开关并显示提示信息可以帮助我们更好地追踪和记录问题。这对于后续的问题排查和系统优化非常有帮助。
  4. 系统监控和管理:通过监控开关状态的变化,我们可以了解系统的运行状况,以及用户对API接口的使用情况。这有助于进行系统性能优化和资源管理。
  5. 用户体验:在某些情况下,当API接口不可用或需要维护时,向用户显示友好的提示信息可以避免用户感到困惑或带来不必要的困扰。同时,提前通知用户也体现了对用户体验的关注。
  6. 合规性和隐私保护:在涉及敏感数据或受限制的API接口中,通过关闭开关并显示提示信息,可以确保遵守相关法规和隐私政策,对数据进行适当的管理和保护。

2. 实现方案

首先,定义一个AOP切面(Aspect),该切面负责控制接口(Controller)的开关行为。

在切面中,我们可以使用Spring AOP的切入点(Pointcut)来指定需要拦截的方法。一旦方法被拦截,我们可以在切面的通知(Advice)中定义相应的默认行为。接下来我们将一步一步的实现接口开关功能。

  • 自定义注解
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface ApiSwitch {


  /**接口对应的key,通过可以该key查询接口是否关闭*/
  String key() default "" ;
  
  /**解析器beanName,通过具体的实现获取key对应的值*/
  String resolver() default "" ;
  
  /**开启后降级方法名*/
  String fallback() default "" ;
  
}
  • 定义解析器接口
public interface SwitchResolver {


  boolean resolver(String key) ;
  
  public void config(String key, Integer onoff) ;
  
}
  • 接口默认实现
@Component
public class ConcurrentMapResolver implements SwitchResolver {


  private Map<String, Integer> keys = new ConcurrentHashMap<>() ;
  
  @Override
  public boolean resolver(String key) {
    Integer value = keys.get(key) ;
    return value == null ? false : (value == 1) ;
  }
  
  public void config(String key, Integer onoff) {
    keys.put(key, onoff) ;
  }
}
  • 基于redis实现
@Component
public class RedisResolver implements SwitchResolver {


  private final StringRedisTemplate stringRedisTemplate ;
  
  public RedisResolver(StringRedisTemplate stringRedisTemplate) {
    this.stringRedisTemplate = stringRedisTemplate ;
  }
  
  @Override
  public boolean resolver(String key) {
    String value = this.stringRedisTemplate.opsForValue().get(key) ;
    return !(value == null || "0".equals(value)) ;
  }


  @Override
  public void config(String key, Integer onoff) {
    this.stringRedisTemplate.opsForValue().set(key, String.valueOf(onoff)) ;
  }
}

这里就提供两种默认的实现。

  • 定义切面
@Component
@Aspect
public class ApiSwitchAspect implements ApplicationContextAware {
  
  private ApplicationContext context ;
  private final SwitchProperties switchProperties ;
  public static final Map<String, Class<? extends SwitchResolver>> MAPPINGS;
  static {
    // 初始化所有的解析器
    Map<String, Class<? extends SwitchResolver>> mappings = new HashMap<>() ;
    mappings.put("map", ConcurrentMapResolver.class) ;
    mappings.put("redis", RedisResolver.class) ;
    MAPPINGS = Collections.unmodifiableMap(mappings) ;
  }
  
  public ApiSwitchAspect(SwitchProperties switchProperties) {
    this.switchProperties = switchProperties ;
  }
  
  @Pointcut("@annotation(apiSwitch)")
  private void onoff(ApiSwitch apiSwitch) {}
  
  @Around("onoff(apiSwitch)")
  public Object ctl(ProceedingJoinPoint pjp, ApiSwitch apiSwitch) throws Throwable {
    
    // 对应接口开关的key
    String key = apiSwitch.key() ;
    // 解析器bean的名称
    String resolverName = apiSwitch.resolver() ;
    // 降级方法名
    String fallback = apiSwitch.fallback() ;
    
    SwitchResolver resolver = null ;
    // 根据指定的beanName获取具体的解析器;以下都不考虑不存在的情况
    if (StringUtils.hasLength(resolverName)) {
      resolver = this.context.getBean(resolverName, SwitchResolver.class) ;
    } else {
      resolver = this.context.getBean(MAPPINGS.get(this.switchProperties.getResolver())) ;
    }
    // 解析器不存在则直接调用目标接口
    if (resolver == null || !resolver.resolver(key)) {
      return pjp.proceed() ;
    }
    // 调用降级的方法;关于降级的方法简单点,都必须在当前接口类中,同时还不考虑方法参数的情况
    if (!StringUtils.hasLength(fallback)) {
      // 未配置的情况
      return "接口不可用" ;
    }
    Class<?> clazz = pjp.getSignature().getDeclaringType() ;
    Method fallbackMethod = clazz.getDeclaredMethod(fallback) ;
    return fallbackMethod.invoke(pjp.getTarget()) ;
  }


  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.context = applicationContext ;
  }
  
}
  • 修改开关接口
@GetMapping("/onoff/{state}")
public Object onoff(String key, @PathVariable("state") Integer state) {
  String resolverType = switchProperties.getResolver();
  if (!StringUtils.hasLength(resolverType)) {
    SwitchResolver bean = this.context.getBean(ApiSwitchAspect.MAPPINGS.get("map")) ;
    if (bean instanceof ConcurrentMapResolver resolver) {
      resolver.config(key, state) ;
    }
  } else {
    SwitchResolver resolver = this.context.getBean(ApiSwitchAspect.MAPPINGS.get(resolverType)) ;
    resolver.config(key, state) ;
  }
  return "success" ; 
}

通过该接口修改具体哪个接口的开关状态。(注意:这里有小问题,如果接口上指定了resolver类型且配置文件中指定的类型不一致,就会出现不生效问题。这个问题大家可以自行解决)

  • 接下来进行测试
@GetMapping("/q1")
@ApiSwitch(key = "swtich$q1", fallback = "q1_fallback", resolver = "redisResolver")
public Object q1() {
  return "q1" ;
}


public Object q1_fallback() {
  return "接口维护中" ;
}

这是完整的配置示例,这里除了key必须外,其它的都可以不填写。

具体测试结果就不贴了,大家可以自行测试基于jvm内存和redis的方式。

总结:通过上述介绍,我们可以看到使用Spring AOP实现接口的开关功能是一种非常有效的方法。通过定义AOP切面和切入点,我们可以精确地拦截需要控制的方法,并在通知中根据开关状态执行相应的逻辑。这种技术手段有助于提高代码的可维护性和可扩展性,同时提供更好的灵活性和控制性来管理接口的行为

责任编辑:武晓燕 来源: Spring全家桶实战案例源码
相关推荐

2018-02-25 22:37:21

应用开关Java

2023-11-07 08:25:34

API接口参数验证

2022-03-08 06:41:35

css代码

2020-04-03 14:55:39

Python 代码编程

2011-10-18 10:40:52

应用系统

2022-12-26 07:47:37

JDK8函数式接口

2020-11-17 09:34:31

API接口后端

2024-02-07 01:47:47

atexit模块程序

2022-09-19 15:02:24

C语言

2022-06-13 08:01:59

WireMockHttp模拟服务

2021-01-14 09:59:07

JS代码编码

2022-04-10 10:41:17

ESLint异步代码

2022-12-12 08:14:47

2021-09-22 11:05:19

JS代码前端

2021-03-09 13:18:53

加密解密参数

2021-07-15 09:47:20

Docker容器命令

2022-06-21 14:44:38

接口数据脱敏

2022-06-04 12:25:10

解密加密过滤器

2020-12-08 08:08:51

Java接口数据

2023-11-23 13:50:00

Python代码
点赞
收藏

51CTO技术栈公众号