The three core concepts of the Spring Cloud Gateway

The route of routing

Can be understood as a forwarding rule containing:

  • id
  • Target url
  • Predicate.
  • If the assertion is true, the request will be routed to the target URL via the filter.

Predicate assertion

This can be understood as a condition that matches the specified rule on the current HTTP request. When the rule matches, the assertion is true, and the request is then routed to the destination address, service, or filter

The filter filter

The logical part that processes the request. When a request’s assertion is true, it is routed to a filter set to process the request. For example, you can add a request header to the request, or add a request parameter, or modify the request URI, and so on.

NACOS acts as the configuration hub for routing rules

The configuration and operation of NACOS is as follows

  • MySQL configuration run
  • Running MySQL

    docker run -p 3306:3306 --name mysql \ -v /Users/wangbin/dockerall/mysql/log:/var/log/mysql \ -v /Users/wangbin/dockerall/mysql/data:/var/lib/mysql \ -v /Users/wangbin/dockerall/mysql/conf:/etc/mysql \ -e MYSQL_ROOT_PASSWORD=root \ -d mysql: 5.5.docker exec-it MySQL bash mysql-proot create database nacos_config; use nacos_config;
  • Execute SQL SQL content
  • Create a new directory/XXXXX /nacos_docker/init.d/ and generate the file custom.properties. The file reads as follows

    management.endpoints.web.exposure.include=* server.contextPath=/nacos server.servlet.contextPath=/nacos server.port=8848 Spring. The datasource. Platform = mysql db. Num = 1 db. Url. 0 = JDBC: mysql: / / 127.0.0.1:3306 / nacos_config? characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true db.user=root db.password=root nacos.cmdb.dumpTaskInterval=3600 nacos.cmdb.eventTaskInterval=10 nacos.cmdb.labelTaskInterval=300 nacos.cmdb.loadDataAtStart=false management.metrics.export.elastic.enabled=false management.metrics.export.influx.enabled=false server.tomcat.accesslog.enabled=true server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i nacos.security.ignore.urls=/,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/** ,/v1/auth/login,/v1/console/health/**,/v1/cs/**,/v1/ns/**,/v1/cmdb/**,/actuator/**,/v1/console/server/** nacos.naming.distro.taskDispatchThreadCount=1 nacos.naming.distro.taskDispatchPeriod=200 Nacos. Naming. Distro. BatchSyncKeyCount = 1000 nacos. Naming. Distro. InitDataRatio = 0.9 nacos. Naming. Distro. SyncRetryDelay = 5000  nacos.naming.data.warmup=true nacos.naming.expireInstance=true
  • New logs directory
  • Run Nacos

    docker run
    --name nacos -d
    -p 8848:8848
    --privileged=true
    --restart=always
    -e JVM_XMS=256m
    -e JVM_XMX=256m
    -e MODE=standalone
    -e PREFER_HOST_MODE=hostname
    -v /xxxxx/nacos_docker/init.d/custom.properties:/home/nacos/init.d/custom.properties
    -v /xxxxx/nacos_docker/logs:/home/nacos/logs
    nacos/nacos-server
    
  • Go to http://localhost:8848
  • Type nacos/nacos to log in

New configuration content

The following

[{
    "id":"user-router",
    "predicates":[
      {
        "args":{
          "pattern": "/usr/**"
        },
        "name": "Path"
      }
    ],
    "filters": [
      {
        "name": "StripPrefix",
        "args": {
          "parts": "1"
        }
      }
    ],
    "uri": "lb://user-service"
}]

The corresponding YML content is shown in the Route section

Spring: Application: Name: DynamicGateway Cloud: Nacos: Discovery: Server-Addr: LocalHost :8848 server-addr: localhost:8848 gateway: discovery: locator: enabled: true routes: - id: user-router uri: Lb ://user-service predicates: -path =/usr/** filters: -stripPrefix =1 #

New project because it uses Spring Cloud, Spring Cloud Alibaba, Nacos version dependencies are as follows

New DynamicGatewayRouteConfig

@Component public class DynamicGatewayRouteConfig implements ApplicationEventPublisherAware { private String dataId = "gateway-router"; private String group = "DEFAULT_GROUP"; @Value("${spring.cloud.nacos.config.server-addr}") private String serverAddr; @Autowired private RouteDefinitionWriter routeDefinitionWriter; private ApplicationEventPublisher applicationEventPublisher; private static final List<String> ROUTE_LIST = new ArrayList<String>(); @PostConstruct public void dynamicRouteByNacosListener() { try { ConfigService configService = NacosFactory.createConfigService(serverAddr); configService.getConfig(dataId, group, 5000); configService.addListener(dataId, group, new Listener() { public void receiveConfigInfo(String configInfo) { clearRoute(); try { List<RouteDefinition> gatewayRouteDefinitions = JSONObject.parseArray(configInfo, RouteDefinition.class); for (RouteDefinition routeDefinition : gatewayRouteDefinitions) { addRoute(routeDefinition); } publish(); } catch (Exception e) { e.printStackTrace(); } } public Executor getExecutor() { return null; }}); } catch (NacosException e) { e.printStackTrace(); } } private void clearRoute() { for (String id : ROUTE_LIST) { this.routeDefinitionWriter.delete(Mono.just(id)).subscribe(); } ROUTE_LIST.clear(); } private void addRoute(RouteDefinition definition) { try { routeDefinitionWriter.save(Mono.just(definition)).subscribe(); ROUTE_LIST.add(definition.getId()); } catch (Exception e) { e.printStackTrace(); } } private void publish() { this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this.routeDefinitionWriter)); } public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; }}

Updates are automatically invoked when the Route content of Nacos changes

The bootstrap.yml contents are as follows

Spring: Application: Name: DynamicGateway Cloud: Nacos: Discovery: Server-Addr: LocalHost :8848 server-addr: localhost:8848 gateway: discovery: locator: enabled: true management: endpoints: web: exposure: include: '*' endpoint: health: show-details: always

Specific code code