Updated on 2023-11-08 GMT+08:00

Customized Governance

The default implementation of service governance does not solve all service problems. The customized governance function allows you to use request marker-based governance capability in different scenarios, for example, rate limiting in the gateway scenario, and URL matching in the Java chassis scenario. The SDK is based on Spring, and all Spring-based frameworks can flexibly use these APIs with similar methods.

The following uses rate limiting as an example to describe how to use an API. You can also use custom API-based code to deliver services and governance rules on the ServiceComb engine management console.

The basic code process includes declaring the reference of RateLimitingHandler, creating GovernanceRequest, intercepting (packaging) the service logic, and handling governance exceptions.

 @Autowired
private RateLimitingHandler rateLimitingHandler;

GovernanceRequest governanceRequest = convert(request);

CheckedFunction0<Object> next = pjp::proceed;
DecorateCheckedSupplier<Object> dcs = Decorators.ofCheckedSupplier(next);

try {
  SpringCloudInvocationContext.setInvocationContext();

  RateLimiter rateLimiter = rateLimitingHandler.getActuator(request);
  if (rateLimiter != null) {
	dcs.withRateLimiter(rateLimiter);
  }

  return dcs.get();
} catch (Throwable th) {
  if (th instanceof RequestNotPermitted) {
	response.setStatus(429);
	response.getWriter().print("rate limited.");
	LOGGER.warn("the request is rate limit by policy : {}",
		th.getMessage());
  } else {
	if (serverRecoverPolicy != null) {
	  return serverRecoverPolicy.apply(th);
	}
	throw th;
  }
} finally {
  SpringCloudInvocationContext.removeInvocationContext();
}

This section describes the customized development. For in-depth usage, you can also refer to the default implementation code in the Java chassis and Spring Cloud projects.