这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos
《Spring Cloud Gateway实战》是欣宸在Java领域的系列原创,旨在通过项目实战与大家一起学习和掌握Spring Cloud Gateway,更好的为实际项目服务
作为《Spring Cloud Gateway实战》的开篇,本文的主要内容如下:
spring: cloud: gateway: # 核心概念1:路由,一个路由代表一个处理逻辑, # 该逻辑里面包含三个元素:匹配条件(是否该此路由处理)、真实处理地址、过滤器 routes: # id要确保唯一性 - id: add_request_header_route # 真实处理地址,请求一旦确定是当前路由处理,就会转发到这个地址去 uri: https://example.org # 核心概念2:谓语或者断言,作用是判断请求是否由当前路由处理 predicates: # 这是断言的一种,检查请求的Cookie中mycookie的值是否等于mycookievalue - Cookie=mycookie,mycookievalue # 核心概念3:过滤器,请求前和请求后都可以有过滤器处理请求响应数据 filters: # 这个过滤器的作用是在请求header中添加一个键值对,值等于"aaabbbccc" - AddRequestHeader=X-Request-Red, aaabbbccc
整个《pring Cloud Gateway实战》系列,我们会涉及到多个服务,这就不可避免的会用到注册中心和配置中心,这里我选择了nacos,它可以很好地承担注册中心和配置中心的角色,接下来介绍如何部署和启动nacos
下载nacos,地址是:https://github.com/alibaba/nacos/releases/download/2.0.3/nacos-server-2.0.3.zip
解压后进入nacos\bin目录,执行以下命令启动nacos:
startup.cmd -m standalone
sh startup.sh -m standalone
浏览器登录nacos,地址是http://localhost:8848/nacos,账号和密码都是nacos
登录成功后显示如下:
名称 | 链接 | 备注 |
---|---|---|
项目主页 | https://github.com/zq2599/blog_demos | 该项目在GitHub上的主页 |
git仓库地址(https) | https://github.com/zq2599/blog_demos.git | 该项目源码的仓库地址,https协议 |
git仓库地址(ssh) | git@github.com:zq2599/blog_demos.git | 该项目源码的仓库地址,ssh协议 |
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <modules> <module>hello-gateway</module> <module>provider-hello</module> <module>common</module> </modules> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.2</version> <relativePath/> </parent> <groupId>com.bolingcavalry</groupId> <artifactId>spring-cloud-tutorials</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <java.version>1.8</java.version> <spring-cloud.version>2020.0.1</spring-cloud.version> <spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version> </properties> <packaging>pom</packaging> <description>Demo project for Spring Cloud </description> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.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>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.14.9</version> <scope>compile</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.7</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version> </dependency> </dependencies> </dependencyManagement> </project>
现在创建名为common的子工程,整个《Spring Cloud Gateway实战》系列涉及的常量和数据结构都放在这个子工程中,方便其他工程使用
新增常量Constants.java:
package com.bolingcavalry.common; public interface Constants { String HELLO_PREFIX = "Hello World"; }
现在创建名为provider-hello的web应用,这是个极其普通的web应用,提供几个http接口服务,咱们在尝试Spring Cloud Gateway的基本功能时,都会将请求路由到provider-hello上来
provider-hello是个普通的springboot应用,会在nacos进行注册,其pom.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-cloud-tutorials</artifactId> <groupId>com.bolingcavalry</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>provider-hello</artifactId> <packaging>jar</packaging> <dependencies> <dependency> <groupId>com.bolingcavalry</groupId> <artifactId>common</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--nacos:用于服务注册与发现--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <!-- 如果父工程不是springboot,就要用以下方式使用插件,才能生成正常的jar --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>com.bolingcavalry.provider.ProviderApplication</mainClass> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
server: #服务端口 port: 8082 spring: application: name: provider-hello cloud: nacos: discovery: # nacos服务地址 server-addr: 127.0.0.1:8848
package com.bolingcavalry.provider; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } }
package com.bolingcavalry.provider.controller; import com.bolingcavalry.common.Constants; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.text.SimpleDateFormat; import java.util.Date; @RestController @RequestMapping("/hello") public class Hello { private String dateStr(){ return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()); } /** * 返回字符串类型 * @return */ @GetMapping("/str") public String helloStr() { return Constants.HELLO_PREFIX + ", " + dateStr(); } }
package com.bolingcavalry.provider.controller; import com.bolingcavalry.common.Constants; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc @Slf4j class HelloTest { @Autowired private MockMvc mvc; @Test void hello() throws Exception { String responseString = mvc.perform(MockMvcRequestBuilders.get("/hello/str").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(containsString(Constants.HELLO_PREFIX))) .andDo(print()) .andReturn() .getResponse() .getContentAsString(); log.info("response in junit test :\n" + responseString); } }
前面做了那么多准备,接下来咱们会投入到Spring Cloud Gateway的开发中,先写个简单的demo快速体验一下
新增名为hello-gateway的子工程,pom.xml如下,重点是依赖了spring-cloud-starter-gateway库,还有一处要重点小心的:测试库用的是reactor-test和spring-boot-starter-test,这和之前的单元测试很不一样,用的是webflux:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-cloud-tutorials</artifactId> <groupId>com.bolingcavalry</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>hello-gateway</artifactId> <dependencies> <dependency> <groupId>com.bolingcavalry</groupId> <artifactId>common</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
server: #服务端口 port: 8081 spring: application: name: hello-gateway cloud: gateway: routes: - id: path_route # 匹配成功后,会被转发到8082端口,至于端口后面的path,会直接使用原始请求的 # 例如http://127.0.0.1:8081/hello/str,会被转发到http://127.0.0.1:8082/hello/str uri: http://127.0.0.1:8082 predicates: # 根据请求路径中带有"/hello/",就算匹配成功 - Path=/hello/**
package com.bolingcavalry.hellogateway.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.util.pattern.PathPatternParser; @Configuration public class CorsConfig { @Bean public CorsWebFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedMethod("*"); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); } }
package com.bolingcavalry.hellogateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HelloGatewayApplication { public static void main(String[] args) { SpringApplication.run(HelloGatewayApplication.class,args); } }
package com.bolingcavalry.hellogateway; import com.bolingcavalry.common.Constants; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.reactive.server.WebTestClient; import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest @ExtendWith(SpringExtension.class) @AutoConfigureWebTestClient public class HelloTest { @Autowired private WebTestClient webClient; @Test void testHelloPredicates() { webClient.get() .uri("/hello/str") .accept(MediaType.APPLICATION_JSON) .exchange() // 验证状态 .expectStatus().isOk() // 验证结果,注意结果是字符串格式 .expectBody(String.class).consumeWith(result -> assertTrue(result.getResponseBody().contains(Constants.HELLO_PREFIX))); } }
程序员欣宸
我是欣宸,期待与您一同畅游Java世界…