当前位置:网站首页>Nacos microservice gateway component +swagger2 interface generation
Nacos microservice gateway component +swagger2 interface generation
2022-07-08 01:48:00 【kjshuan】
- Spring Cloud Gateway Quick start
- Environment building
1. Introduce dependencies
Main item
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.2.RELEASE</spring-boot.version>
<spring-cloud.version>Hoxton.SR9</spring-cloud.version>
<spring-cloud-alibaba.version>2.2.6.RELEASE</spring-cloud-alibaba.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
subprojects 1
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
subprojects 2 gateway
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
Be careful : Hui He spring-webmvc The conflict of dependence , Need to be excluded spring-webmvc
2. To write yml The configuration file
subprojects 1
server:
port: 9001
spring:
application:
name: stockmodule
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.64.135:3306/mydemo?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8&autoReconnect=true
username: root
password: 3090_Cmok
cloud:
nacos:
discovery:
server-addr: 192.168.64.135:8848
username: nacos
password: nacos
namespace: public
subprojects 2 gateway
server:
port: 9002
spring:
application:
name: gateway
cloud:
gateway:
routes:
- id: stockservices
uri: lb://stockmodule
predicates:
- Path=/xxx/**
# - After=2022-07-01T16:59:59.259+08:00[Asia/Shanghai]
# - Header=token,\d+
- Method=GET
- Query=tt,12
filters:
- StripPrefix=1
- AddRequestHeader=token,123456
nacos:
discovery:
server-addr: 192.168.64.135:8848
username: nacos
password: nacos
namespace: public
Integrate Nacos
Now write the address of the forwarding path in the configuration file , We have analyzed the problems caused by dead address writing , Next, we get this address from the registry .
1. Introduce dependencies
To write yml The configuration file
Abbreviation : Remove the routing configuration , Auto find service
Write subprojects 1 (domian mapper service controller)
#domain
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ApiModel(" Commodity inventory ")
public class Stocks {
@ApiModelProperty(" Stock number ")
private Integer id;
@ApiModelProperty(" Product id ")
private Integer shopid;
@ApiModelProperty(" Current number ")
private Integer storenum;
}
#mapper Interface
@Mapper
public interface StockMapper extends BaseMapper<Stocks> {
}
#service Interface
public interface StockServic {
public List<Stocks> findStock();
}
#service Implementation class
@Service
public class StockServicImpl extends ServiceImpl<StockMapper, Stocks> implements StockServic {
@Override
public List<Stocks> findStock() {
return this.list();
}
}
#controller layer
@RestController
@RequestMapping("/stock-serv")
@Api(value = " Inventory service API")
//public class StockCtrl {
// @Resource
// private StockServic stockServic;
@RequestHeader("token")String token
//
// @ApiOperation(value = " Query the current inventory of all goods ",httpMethod = "GET")
// @ApiImplicitParams({
// @ApiImplicitParam(name = "id",value = " user id",required = true,dataType = "int",paramType ="query")
// })
// @RequestMapping(value = "/findall")
// public List<Stocks> findAll(@RequestParam("id") int id){
System.out.println(" Get header information token:============》"+token);
// return stockServic.findStock();
// }
//}
public class StockCtrl {
@Resource
private StockServic stockServic;
// @RequestHeader("token")String token
@RequestMapping(value = "/findall")
public List<Stocks> findAll(){
// System.out.println(" Get header information token:============》"+token);
return stockServic.findStock();
}
}
swagger To configure
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
// Configure the information on the interface page
public ApiInfo apiInfo(){
return new ApiInfoBuilder().title(" Gateway project interface test ")
.description(" Test interface description ")
.version("v1.0")
.termsOfServiceUrl("http://www.baidu.com")
.contact(" The programmer ")
.build();
}
}
3) test
Now , I found that as long as the gateway address /
http://localhost:9001/stock-serv/findall
# Configure the gateway browsing address
http://localhost:9002/xxx/stock-serv/findall
- Route assertion factory (Route Predicate Factories) To configure
effect : When requested gateway When , Use assertions to match requests , If the match is successful, route and forward , Returns if the match fails 404 type : built-in , Customize
SpringCloud Gateway Includes many built-in assertion factories , All these assertions relate to HTTP The different properties of the request match . As follows :
be based on Datetime Assertion factory of type
This type of assertion is judged by time , There are three main ones :
AfterRoutePredicateFactory: Receive a date parameter , Determine whether the request date is later than the specified date BeforeRoutePredicateFactory: Receive a date parameter , Determine whether the request date is earlier than the specified date BetweenRoutePredicateFactory: Receive two date parameters , Determine whether the request date is within the specified time period ZonedDateTime.now()
Assertion factory based on remote address
RemoteAddrRoutePredicateFactory: Receive one IP Address segment , Determine whether the request host address is in the address section
be based on Cookie The assertion factory of
CookieRoutePredicateFactory: Receive two parameters ,cookie Name and a regular expression . Judge the request cookie Whether it has the given name and the value matches the regular expression .
1 | ‐Cookie | =chocolate, ch. |
be based on Header The assertion factory of
HeaderRoutePredicateFactory: Receive two parameters , Title names and regular expressions . Judge the request Header Whether it has the given name and the value matches the regular expression .
be based on Host The assertion factory of
HostRoutePredicateFactory: Receive a parameter , Host name mode . Judge requested Host Whether the matching rules are met .
be based on Method Assertion factory for request method
MethodRoutePredicateFactory: Receive a parameter , Determine whether the request type matches the specified type .
1 | ‐Method | =GET |
be based on Path Assertion factory for request path
PathRoutePredicateFactory: Receive a parameter , Judge requested URI Whether the part satisfies the path rule .
be based on Query Assertion factory for request parameters
QueryRoutePredicateFactory : Receive two parameters , request param And regular expressions , Determine whether the request parameter has a given name and the value matches the regular expression .
Assertion factory based on routing weight
WeightRoutePredicateFactory: Receive one [ Group name , The weight ], Then for the routes in the same group, they are forwarded according to the weight
2.2.5 Custom route assertion factory
Custom route assertion factories need to inherit AbstractRoutePredicateFactory class , rewrite apply The logic of the method . stay apply In the method, you can use exchange.getRequest() Get ServerHttpRequest object , So you can get the parameters of the request 、 Request mode 、 Ask for first-class information .
1、 must spring Components bean
- Class must be added RoutePredicateFactory As the end
- Must inherit AbstractRoutePredicateFactory
- You must declare a static inner class Declare properties to receive The information of the corresponding assertion in the configuration file
- Need to combine shortcutFieldOrder Binding 6. adopt apply Make logical judgments true It's a match false Matching failure
Be careful : Naming needs to be done with RoutePredicateFactory ending
[email protected]
[email protected]
3public class CheckAuthRoutePredicateFactory extends AbstractRoutePredicateFactory<CheckAuthRoutePredicateFactory.Con fig> {
4
5public CheckAuthRoutePredicateFactory() {
6super(Config.class);
7 }
8
[email protected]
10public Predicate<ServerWebExchange> apply(Config config) {
11return new GatewayPredicate() {
12
[email protected]
14public boolean test(ServerWebExchange serverWebExchange) {
15log.info(" call CheckAuthRoutePredicateFactory" + config.getName());
16if(config.getName().equals("xushu")){
17return true;
18 }
19 return false;
20 }
21 };
22 }
23
24 /**
25* Quick configuration
26* @return
27 */
[email protected]
29public List<String> shortcutFieldOrder() {
30return Collections.singletonList("name");
31 }
32
33 public static class Config {
34
35 private String name;
36
37public String getName() {
38return name;
39 }
40
41public void setName(String name) {
42this.name = name;
43 }
44 }
45 }
yml Middle configuration
| ||
12 | ‐ CheckAuth | =xushu |
- Filter factory ( GatewayFilter Factories) To configure
Gateway Built in many filter factories , We can process some business logic processors through some filter factories , For example, add and reject response headers , Add and remove parameters, etc
Filter factory | effect | Parameters |
AddRequestHeader | Add... For the original request Header | Header Name and value of |
AddRequestParameter | Add request parameters to the original request | Parameter name and value |
AddResponseHeader | Add... For the original response Header | Header Name and value of |
DedupeResponseHeader | Remove duplicate values from the response header | Need to remove heavy Header Name and de duplication strategy |
Hystrix | Introduce... For routing Hystrix Circuit breaker protection | HystrixCommand The name of |
FallbackHeaders | by fallbackUri Add specific exception information to the request header of | Header The name of |
PrefixPath | Prefix the original request path | prefix path |
PreserveHostHeader | Add a... For the request preserveHostHeader=true Of Belong to sex , The routing filter checks this property to determine whether to send the original Host | nothing |
RequestRateLimiter | Used to limit the flow of requests , The current limiting algorithm is token bucket | keyResolver、rateLimiter、statusCode、denyEmptyKey、emptyKeyStatus |
RedirectTo | Redirect the original request to the specified URL | http Status code and redirection url |
RemoveHopByHopHeadersFilter | Delete... For original request IETF A series of organizational rules Header | It is enabled by default , You can configure to specify only which Header |
RemoveRequestHeader | Delete a... For the original request Header | Header name |
RemoveResponseHeader | Delete a... For the original response Header | Header name |
RewritePath | Rewrite the original request path | The original path regular expression and the rewritten path regular expression |
RewriteResponseHeader | Rewrite one of the original responses Header | Header name , Positive of value Expression , Overridden value |
SaveSession | Before forwarding the request , Enforcement WebSession::save operation | nothing |
secureHeaders | Add a series of security response headers to the original response | nothing , Support to modify the value of these security response headers |
SetPath | Modify the original request path | The modified path |
SetResponseHeader | Modify one of the original responses Header Value | Header name , Modified value |
SetStatus | Modify the status code of the original response | HTTP Status code , It could be a number , It could be a string |
StripPrefix | Used to truncate the path of the original request | Use numbers to indicate the number of paths to truncate |
Retry | Retry for different responses | retries、statuses、methods、series |
Set the size that allows the largest request packet to be received Small . If the request package size exceeds the set value , Then return to 413 Payload Too | Request package size , The unit is byte , The default value is 5M |
RequestSize | Large | |
Modify the original request body before forwarding the request | The content of the modified request body | |
ModifyRequestBody | ||
ModifyResponseBody | Modify the content of the original response body | The content of the modified response body |
- Add request header
test http://localhost:8888/order/testgateway
- Add request parameters
test http://localhost:8888/order/testgateway3
- Add a uniform prefix to the matching routes
mall-order You need to configure
| |||
3 context | ‐path: | /mall | ‐order |
test :http://localhost:8888/order/findOrderByUserId/1 ====》 http://localhost:8020/mallorder/order/findOrderByUserId/1
- Redirection operation
test :http://localhost:8888/order/findOrderByUserId/1
- Custom filter factory
Inherit AbstractNameValueGatewayFilterFactory And our custom name must be marked with GatewayFilterFactory End and give it to spring management .
Configure custom filter factory
test
Global filter (Global Filters) To configure
The difference between local filter and global filter :
Local : Local for a route , You need to configure the global in the route : For all routing requests , Once defined, it will be put into use
GlobalFilter Interface and GatewayFilter Have the same interface definition , It's just , GlobalFilter Will work on all routes .
- LoadBalancerClientFilter
LoadBalancerClientFilter Will view exchange Properties of ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR Value ( One URI), If the value is scheme yes lb, such as :lb://myservice , It will use Spring Cloud Of LoadBalancerClient to myservice To translate into actual host and port, And replace ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR The content of .
In fact, it is used to integrate load balancers Ribbon Of
| |
8 | ‐ Path=/order/** |
- Custom global filter
To enable the Reactor Netty Access log , Please set up Dreactor.netty.http.server.accessLogEnabled=true.
It has to be Java System attribute , instead of Spring Boot attribute .
You can configure the logging system to have a separate access log file . The following example creates a Logback To configure :
example 67.logback.xml
- Gateway Cross domain configuration (CORS Configuration)
adopt yml Configuration mode
adopt java Configuration mode
- gateway Integrate sentinel Flow control degradation
The gateway serves as a barrier outside the internal system , It has a certain protective effect on the inside , Current limiting is one of them . The current limit of the gateway layer can simply limit the current for different routes , You can also limit the current for the business interface , Or group current limiting according to the characteristics of the interface . Gateway current limiting · alibaba/Sentinel Wiki · GitHub
1. Add dependency
2. Add the configuration
- Console implementation :
Sentinel 1.6.3 The support of gateway flow control console is introduced , Users can directly Sentinel Check on the console API Gateway In real time route And customization API Group monitoring , Manage gateway rules and API Packet allocation .
from 1.6.0 Version start ,Sentinel Provides Spring Cloud Gateway The adaptation module of , It can provide two kinds of restriction flow of resource dimensions : route dimension : That is to say Spring The route entry configured in the configuration file , The resource name is the corresponding routeId
Customize API dimension : Users can take advantage of Sentinel Provided API From defining something API grouping
Custom exception method : 1. adopt yml
1 spring:cloud.sentinel.scg.fallback.mode | = response | ||
2 spring.cloud.sentinel.scg.fallback.response | ‐body | = '{"code":403,"mes":" Current limiting "}' |
2. adopt GatewayCallbackManager
2.6.1 Code implementation :( understand )
The user can go through GatewayRuleManager.loadRules(rules) Manually load gateway rules GatewayConfiguration Add
- Gateway high availability
In order to ensure Gateway High availability , You can start multiple Gateway Instance load , stay Gateway Upstream use of Nginx perhaps F5 Load forwarding for high availability .
边栏推荐
- Coordinate conversion of one-dimensional array and two-dimensional matrix (storage of matrix)
- Codeforces Round #633 (Div. 2) B. Sorted Adjacent Differences
- 快速熟知XML解析
- Dataworks duty table
- 能力贡献 GBASE三大解决方案入选“金融信创生态实验室-金融信创解决方案(第一批)”
- Codeforces Round #649 (Div. 2)——A. XXXXX
- How does Matplotlib generate multiple pictures in turn & only save these pictures without displaying them in the compiler
- 滑环在直驱电机转子的应用领域
- pb9.0 insert ole control 错误的修复工具
- Apache多个组件漏洞公开(CVE-2022-32533/CVE-2022-33980/CVE-2021-37839)
猜你喜欢
Problems of font legend and time scale display of MATLAB drawing coordinate axis
Voice of users | understanding of gbase 8A database learning
Redis cluster
Why did MySQL query not go to the index? This article will give you a comprehensive analysis
从Starfish OS持续对SFO的通缩消耗,长远看SFO的价值
COMSOL----微阻梁模型的搭建---最终的温度分布和变形情况----几何模型的建立
QT -- package the program -- don't install qt- you can run it directly
Sum of submatrix
About snake equation (5)
用户之声 | 对于GBase 8a数据库学习的感悟
随机推荐
从cmath文件看名字是怎样被添加到命名空间std中的
给刚入门或者准备转行网络工程师的朋友一些建议
3. Multi agent reinforcement learning
Apache多个组件漏洞公开(CVE-2022-32533/CVE-2022-33980/CVE-2021-37839)
About snake equation (5)
Why does the updated DNS record not take effect?
跨模态语义关联对齐检索-图像文本匹配(Image-Text Matching)
regular expression
Redux usage
PHP to get information such as audio duration
Sum of submatrix
The body has a mysterious margin of 8px
由排行榜实时更新想到的数状数值
快手小程序担保支付php源码封装
2、TD+Learning
break net
子矩阵的和
ANSI / nema- mw- 1000-2020 magnetic iron wire standard Latest original
cv2-drawline
Apache multiple component vulnerability disclosure (cve-2022-32533/cve-2022-33980/cve-2021-37839)