On the premise of realizing grayscale publishing and routing functions, Nepxion Discovery framework combined with Nacos and Sentinel implemented another layer of protection measures for traffic, which could better achieve the purpose of enterprise-level traffic security control. Its features include:

  • Encapsulates the read logic of the remote configuration center and the local rule file. That is, the remote configuration is read first. If the remote configuration does not exist or the rule is incorrect, the local rule file is read. Dynamically implement hot refreshing of rules by remote configuration center
  • Package NacosDataSource and ApolloDataSource, support Nacos and Apollo two remote configuration centers, zero code to achieve Sentinel function. For more remote configuration centers, see Sentinel’s official DataSource and integrate them yourself
  • Supports native flow control rules, degradation rules, authorization rules, system rules, and hotspot parameter flow control rules
  • The LimitApp mechanism is extended. The combined protection mechanism is implemented through dynamic Http Header, including the protection mechanism based on service name, gray level group, gray level version, gray level region, machine address and port. Any combination of service parameters can be customized to achieve this function. According to the incoming micro service gray version number + user name, combine them together for fusing
  • In addition, rules can be written in micro-service Actuator, Swagger, and Rest modes
  • In the console, users can write rules in batches using microservice name actuators, Swagger, and Rest
  • Support switch off this spring. The application. The strategy. The sentinel. Enabled = true, is off by default
[Nacos] Alibaba middleware department develops a new generation of middleware that integrates service registration discovery center and configuration center. It is a service infrastructure for building modern “service” centric application architectures (e.g., microservice paradigm, cloud native paradigm), supporting the discovery, configuration and management of almost all mainstream types of “services”, and making it more agile and easy to build, deliver and manage microservice platforms

[Sentinel] Alibaba middleware department developed a new generation of traffic as the entry point, from flow control, fuse downgrading, system load protection and other dimensions to protect the stability of distributed system traffic defense. It carries on the core scenarios of Alibaba’s double Eleven traffic promotion in the past 10 years, such as SEC kill (i.e. burst traffic control within the range of system capacity), message peaking and valley filling, cluster flow control, real-time fusing of downstream unavailable applications, etc

Environment setup and dependency introduction

The server introduces the following dependencies in addition to the existing dependencies of the Discovery framework

<dependency>
    <groupId>com.nepxion</groupId>
    <artifactId>discovery-plugin-strategy-starter-service-sentinel</artifactId>
    <version>${discovery.version}</version> </dependency> <dependency> <groupId>com.nepxion</groupId> <artifactId>discovery-plugin-strategy-sentinel-starter-nacos</artifactId> <! -- <artifactId>discovery-plugin-strategy-sentinel-starter-apollo</artifactId> --> <version>${discovery.version}</version>
</dependency>Copy the code

Native Sentinel annotation

See the code below to add the @SentinelResource annotation to the interface method. Value is sentinel-Resource, and blockHandler and Fallback are the methods that need to be executed to protect their effects

@RestController
@ConditionalOnProperty(name = DiscoveryConstant.SPRING_APPLICATION_NAME, havingValue = "discovery-guide-service-b")
public class BFeignImpl extends AbstractFeignImpl implements BFeign {
    private static final Logger LOG = LoggerFactory.getLogger(BFeignImpl.class);

    @Override
    @SentinelResource(value = "sentinel-resource", blockHandler = "handleBlock", fallback = "handleFallback")
    public String invoke(@PathVariable(value = "value") String value) {
        value = doInvoke(value);

        LOG.info("Call path: {}", value);

        return value;
    }

    public String handleBlock(String value, BlockException e) {
        return value + "-> B server sentinel block, cause=" + e.getClass().getName() + ", rule=" + e.getRule() + ", limitApp=" + e.getRuleLimitApp();
    }

    public String handleFallback(String value) {
        return value + "-> B server sentinel fallback"; }}Copy the code

Native Sentinel rule

Sentinel subscribes to the Key format in the configuration center as follows:

Nacos Key format: Group is [Group name] configured in metadata, Data Id is [service name]-[rule type] 2. Apollo Key format: [Group name]-[service name]-[rule type]Copy the code
For usage of Sentinel rules, see the Sentinel official documentation

Flow control rules

Add a rule for discovery-guide-service-b service, where Group is discovery-guide-group and Data Id is discovery-guide-service-b-sentinel-flow. The rule content is as follows:

[{"resource": "sentinel-resource"."limitApp": "default"."grade": 1,
        "count": 1,
        "strategy": 0."refResource": null,
        "controlBehavior": 0."warmUpPeriodSec": 10,
        "maxQueueingTimeMs": 500,
        "clusterMode": false."clusterConfig": null
    }
]Copy the code
As is shown in



Drop rules

Service discovery guide-service-b is added. The Group is discovery-guide-group and the Data Id is discovery-guide-service-b-sentinel-b. The rule includes the following contents:

[{"resource": "sentinel-resource"."limitApp": "default"."count": 2."timeWindow": 10,
        "grade": 0."passCount": 0}]Copy the code
As is shown in



Authorization rules

Add rule discovery-guide-service-b to discovery-guide-group and Data Id to discovery-guide-service-b-sentinel-authority. Add rule discovery-guide-service-b to discovery-guide-service-b. The rules are as follows:

[{"resource": "sentinel-resource"."limitApp": "discovery-guide-service-a"."strategy": 0}]Copy the code
As is shown in



Rules of the system

Add a rule for discovery-guide-service-b service, where Group is discovery-guide-group and Data Id is discovery-guide-service-b-sentinel-system. The rule content is as follows:

[{"resource": null,
        "limitApp": null,
        "highestSystemLoad": 1.0,"highestCpuUsage": 1.0,"qps": 200.0."avgRt": 1,"maxThread"1}] : -Copy the code
As is shown in



Hotspot parameter flow control rule

Add rule for discovery-guide-service-b service, Group = discovery-guide-group, Data Id = discovery-guide-service-b-sentinel-param-flow, The rules are as follows:

[{"resource": "sentinel-resource"."limitApp": "default"."grade": 1,
        "paramIdx": 0."count": 1,
        "controlBehavior": 0."maxQueueingTimeMs": 0."burstCount": 0."durationInSec": 1,
        "paramFlowItemList": []."clusterMode": false}]Copy the code
As is shown in



Protection mechanism based on grayscale routing and Sentinel-LimitApp extension

This method is valid for all the above five rules. The authorization rules are described here

If there are multiple limitApp authorization rules, separate them with commas (,). Strategy “: 0 indicates the whitelist, and “strategy”: 1 indicates the blacklist

Service name-based protection mechanism

Set the Sentinel Request Origin Key to the Header name of the service name and set limitApp to the corresponding service name in the authorization rule to implement name-based defense mechanism

Configuration item. The default configuration item is n-d-service-id. You do not need to configure this item

spring.application.strategy.service.sentinel.request.origin.key=n-d-service-idCopy the code
Add rule discovery-guide-service-b to discovery-guide-group and Data Id to discovery-guide-service-b-sentinel-authority. Add rule discovery-guide-service-b to discovery-guide-service-b. If the rule content is as follows, all discovery-guide-service-a services can access discovery-guide-service-b services

[{"resource": "sentinel-resource"."limitApp": "discovery-guide-service-a"."strategy": 0}]Copy the code

Protection mechanism based on grayscale group

Change the Sentinel Request Origin Key configuration item to the Header name of a grayscale group and change limitApp in the authorization rule to the corresponding group name to implement the name-based defense mechanism

Configuration items

spring.application.strategy.service.sentinel.request.origin.key=n-d-service-groupCopy the code
Add rule discovery-guide-service-b to discovery-guide-group and Data Id to discovery-guide-service-b-sentinel-authority. Add rule discovery-guide-service-b to discovery-guide-service-b. If the rule content is as follows, all services belonging to the my-group are allowed to access discovery-guide-service-b

[{"resource": "sentinel-resource"."limitApp": "my-group"."strategy": 0}]Copy the code

Protection mechanism based on grayscale version

Change the Sentinel Request Origin Key configuration item to the Header name of the grayscale version, and change limitApp in the authorization rule to the corresponding version to implement versio-based defense

Configuration items

spring.application.strategy.service.sentinel.request.origin.key=n-d-service-versionCopy the code
Add rule discovery-guide-service-b to discovery-guide-group and Data Id to discovery-guide-service-b-sentinel-authority. Add rule discovery-guide-service-b to discovery-guide-service-b. The content of the rule is as follows, indicating that all services of version 1.0 are allowed to access discovery-guide-service-b

[{"resource": "sentinel-resource"."limitApp": "1.0"."strategy": 0}]Copy the code

Protection mechanism based on gray area

Set the Sentinel Request Origin Key to the Header name of a gray area and set limitApp to the corresponding area in an authorization rule to implement region-based defense

Configuration items

spring.application.strategy.service.sentinel.request.origin.key=n-d-service-regionCopy the code
Add rule discovery-guide-service-b to discovery-guide-group and Data Id to discovery-guide-service-b-sentinel-authority. Add rule discovery-guide-service-b to discovery-guide-service-b. The following rule indicates that all services in dev are allowed to access discovery-guide-service-b

[{"resource": "sentinel-resource"."limitApp": "dev"."strategy": 0}]Copy the code

Protection mechanism based on machine address and port

If the Sentinel Request Origin Key is set to the Header name of the gray area and limitApp is set to the corresponding area value in the authorization rule, the protection mechanism based on the machine address and port can be implemented

Configuration items

spring.application.strategy.service.sentinel.request.origin.key=n-d-service-addressCopy the code
Add rule discovery-guide-service-b to discovery-guide-group and Data Id to discovery-guide-service-b-sentinel-authority. Add rule discovery-guide-service-b to discovery-guide-service-b. Discovery-guide-service-b is allowed for services whose IP addresses and ports are 192.168.0.88:8081 and 192.168.0.88:8082

[{"resource": "sentinel-resource"."limitApp": "192.168.0.88:8081192168 0.88:8082"."strategy": 0}]Copy the code

Combined protection mechanism for user-defined service parameters

The combined protection mechanism of user-defined service parameters is realized through adaptation classes

// Version number + username, Implement sectional fusing public class MyServiceSentinelRequestOriginAdapter extends DefaultServiceSentinelRequestOriginAdapter { @Override public String parseOrigin(HttpServletRequest request) { String version = request.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION); String user = request.getHeader("user");

        return version + "&"+ user; }}Copy the code
Create adaptive classes in @bean mode in the configuration class

@Bean
public ServiceSentinelRequestOriginAdapter ServiceSentinelRequestOriginAdapter() {
    return new MyServiceSentinelRequestOriginAdapter();
}Copy the code
Add rule discovery-guide-service-b to discovery-guide-group and Data Id to discovery-guide-service-b-sentinel-authority. Add rule discovery-guide-service-b to discovery-guide-service-b. The content of the rule is as follows, indicating that the version is 1.0 and the user of Http Header is =zhangsan. All services that meet the two conditions are allowed to access discovery-guide-service-b

[{"resource": "sentinel-resource"."limitApp": "1.0 & zhangsan"."strategy": 0}]Copy the code
Running effect

  • When user=zhangsan in the Http Header passed, when the full link call is in progress, API gateway load balancing discovery-guide-service-a service is called after version 1.0, and finally the call succeeds
As is shown in



  • When user=lisi is passed in the Http Header, the final call is rejected on the discovery-guide-service-b server
As is shown in



  • When user=zhangsan in Http Header is passed, one of the conditions is met. When the full link invocation, API gateway load balance discovery-guide-service-a service to version 1.1 and then call discovery-guide-service-b service. The final call was rejected on the discovery-guide-service-b server because version=1.0 was not met
As is shown in



Sentinel rule push based on Swagger

It can be divided into Sentinel rule push based on a single service instance and multiple service instances corresponding to the service name

Sentinel rule push based on a single service instance

Go directly to the Swagger home page of the service instance

As is shown in



Push Sentinel rules based on multiple service instances corresponding to service names

You need to start the Discovery-Console service and access its Swagger home page

As is shown in



Author: Ren Haojun, more than 10 years of open source experience, Github ID: @Haojunren, founder of Nepxion open Source community, Nacos Group Member, Spring Cloud Alibaba & Nacos & Sentinel Committer, used to work in Platform Architecture Department of Ping An Bank, Responsible for the development of basic service framework of bank PaaS system. Weihua Wang, Java developer for more than 10 years, Github ID: @vipweihua, has been studying microservice architecture for many years. Currently, he focuses more on gateway, fusing limit and grayscale routing in microservices. He is now working in The Platform Architecture Department of Ping An Bank, engaged in the development of basic service framework of bank PaaS system.



The original link

This article is the original content of the cloud habitat community, shall not be reproduced without permission.