网站建设能力,外接硬盘做创建立网站,小程序商城哪的服务好,閪是什么意思Gateway配置与使用 前言新建gateway子项目pom.xml配置文件启动类访问接口方式 测试拓展 前言
在工作中遇到一种情况#xff0c;一个父项目中有两个子项目。实际使用时#xff0c;需要外网可以访问#xff0c;宝信软件只能将一个端口号发布在外网上#xff0c;所以需要运用… Gateway配置与使用 前言新建gateway子项目pom.xml配置文件启动类访问接口方式 测试拓展 前言
在工作中遇到一种情况一个父项目中有两个子项目。实际使用时需要外网可以访问宝信软件只能将一个端口号发布在外网上所以需要运用网关技术通过一个端口号访问两个项目。 之前已经试用nacos搭建了注册中心
新建gateway子项目
pom.xml
导入依赖时注意SpringCloudAlibaba与gateway依赖的版本是否对应否则启动时会报错。
?xml version1.0 encodingUTF-8?
project xmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdparentartifactIdtestmaven32springcloud/artifactIdgroupIdcom.hzx/groupIdversion1.0-SNAPSHOT/version/parentmodelVersion4.0.0/modelVersionartifactIdgateway-project/artifactIddependencies!-- 此依赖已经在父项目pom中导入dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactId/dependency--dependencygroupIdcom.alibaba.cloud/groupIdartifactIdspring-cloud-starter-alibaba-nacos-discovery/artifactIdversion2.2.7.RELEASE/version/dependencydependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-gateway/artifactIdversion2.2.6.RELEASE/version/dependency/dependencies
/project配置文件
将gateway服务注册到nacos中
server:port: 8901
spring:cloud:nacos:discovery:server-addr: http://192.168.0.248:8848namespace: e6f0f8ad-e4c1-408b-afae-4a2495911ca7gateway:discovery:locator:enabled: trueapplication:name: nacos-gateway
启动类
在启动类中需要加上注解EnableDiscoveryClient
SpringBootApplication
EnableDiscoveryClient
public class StartGatewayApplication {public static void main(String[] args) throws Exception {SpringApplication.run(StartGatewayApplication.class, args);}
}以上就是gateway相关的代码启动成功后就可以使用了。 我在学习的时候没想到这么简单。
访问接口方式 http://ip:网关端口/nacos中注册的服务名称/controller层路径 具体内容见测试部分
测试
上一篇讲nacos的文章中我创建了两个子项目分别是nacos-provider-project、nacos-consumer-project连同gateway项目启动后在nacos可以看到注册的服务。 在nacos-provider-project项目添加接口 RequestMapping(value /send/provider/{msg},method RequestMethod.GET)public String sendMessageProvider(PathVariable String msg){return 调用生产者端接口向生产者发送消息msg;}在nacos-consumer-project项目添加接口 RequestMapping(value /send/consumer/{msg},method RequestMethod.GET)public String sendMessageConsumer(PathVariable String msg){return 调用消费者端接口向消费者发送消息msg;}通过接口文档测试上面的两个接口 首先是直接通过项目本身的端口号访问接口。其中8081和8091分别是两个项目的端口号。 然后通过网关端口分别访问两个接口。其中8901为gateway项目端口号nacos-provider与nacos-consumer分别为两个项目在nacos注册中心的服务名称。
拓展
本文中使用的是gateway默认配置网关的方法开发者还可以自定义配置路由也可以不通过注册在nacos中的服务名就能访问接口但这两种方法目前本人还不需要所以文章中没有写出。