Spring Cloud Gateway实战之一:初探

  • 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”>

spring-cloud-tutorials

com.bolingcavalry

1.0-SNAPSHOT

4.0.0

provider-hello

jar

com.bolingcavalry

common

${project.version}

org.springframework.boot

spring-boot-starter-web

com.alibaba.cloud

spring-cloud-starter-alibaba-nacos-config

com.alibaba.cloud

spring-cloud-starter-alibaba-nacos-discovery

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-maven-plugin

com.bolingcavalry.provider.ProviderApplication

repackage

  • 工程的配置文件application.yml如下,web端口是8082,还有一处要注意的是nacos服务地址:

server:

#服务端口

port: 8082

spring:

application:

name: provider-hello

cloud:

nacos:

discovery:

nacos服务地址

server-addr: 127.0.0.1:8848

  • 启动类ProviderApplication.java

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);

}

}

  • 普通的Controller类Hello.java,对外提供一个http服务:

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();

}

}

  • 新增测试类HelloTest.java,用于检查应用的服务是否正常:

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);

}

}

  • 执行单元测试(此时nacos是否启动无所谓,只是不启动的话控制台会有一些错误信息,但是没有影响),如下,测试通过表示服务是正常的:

在这里插入图片描述

开发一个简单的demo,完成spring-cloud-gateway的初体验

  • 前面做了那么多准备,接下来咱们会投入到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”>

spring-cloud-tutorials

com.bolingcavalry

1.0-SNAPSHOT

4.0.0

hello-gateway

com.bolingcavalry

common

${project.version}

org.springframework.cloud

spring-cloud-starter-gateway

io.projectreactor

reactor-test

test

org.springframework.boot

spring-boot-starter-test

test

  • 下面是重点,Spring Cloud Gateway的配置文件application.yml,:

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);

}

}

  • 最后是单元测试类,请注意,由于Spring Cloud Gateway使用了webflux技术栈,因此不能用常见的MockMvc来模拟请求,几个注解也值得注意,另外也要注意WebTestClient的expectStatus、expectBody等API的用法:

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”)

最后总结我的面试经验

2021年的金三银四一眨眼就到了,对于很多人来说是跳槽的好机会,大厂面试远没有我们想的那么困难,摆好心态,做好准备,你也可以的。

另外,面试中遇到不会的问题不妨尝试讲讲自己的思路,因为有些问题不是考察我们的编程能力,而是逻辑思维表达能力;最后平时要进行自我分析与评价,做好职业规划,不断摸索,提高自己的编程能力和抽象思维能力。

BAT面试经验

实战系列:Spring全家桶+Redis等

其他相关的电子书:源码+调优

面试真题:

@AutoConfigureWebTestClient

public class HelloTest {

@Autowired

private WebTestClient webClient;

@Test

void testHelloPredicates() {

webClient.get()

.uri(“/hello/str”)

最后总结我的面试经验

2021年的金三银四一眨眼就到了,对于很多人来说是跳槽的好机会,大厂面试远没有我们想的那么困难,摆好心态,做好准备,你也可以的。

另外,面试中遇到不会的问题不妨尝试讲讲自己的思路,因为有些问题不是考察我们的编程能力,而是逻辑思维表达能力;最后平时要进行自我分析与评价,做好职业规划,不断摸索,提高自己的编程能力和抽象思维能力。

[外链图片转存中…(img-L2mPsa4C-1714453944147)]

BAT面试经验

实战系列:Spring全家桶+Redis等

[外链图片转存中…(img-V20MIjUz-1714453944148)]

其他相关的电子书:源码+调优

[外链图片转存中…(img-ICv035t3-1714453944148)]

面试真题:

[外链图片转存中…(img-TlBZnad2-1714453944149)]

[外链图片转存中…(img-Hulnu1g0-1714453944149)]

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值