SpringCloud + Consul服务注册中心 + gateway网关
?
1? 啟動(dòng)Consul
2? 創(chuàng)建springcloud-consul項(xiàng)目及三個(gè)子模塊
? ? ? ?2.1 數(shù)據(jù)模塊consul-producer
? ? ? ?2.2 數(shù)據(jù)消費(fèi)模塊consul-consumer
? ? ? ?2.3 gateway網(wǎng)關(guān)模塊
3? 測試及項(xiàng)目下載
??
1、首先安裝Consul并啟動(dòng)Consul,端口號(hào)為8500
2、創(chuàng)建一個(gè)maven項(xiàng)目springcloud-consul,修改pom.xml添加SpringBoot及SpringCloud依賴(這里展示的是最后的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"><modelVersion>4.0.0</modelVersion><groupId>com.test</groupId><artifactId>springcloud-consul</artifactId><packaging>pom</packaging><version>1.0-SNAPSHOT</version><modules><module>consul-producer</module><module>consul-consumer</module><module>gateway-service</module></modules><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.4.RELEASE</version><relativePath/></parent><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></dependencies></dependencyManagement><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><spring-cloud.version>Finchley.RELEASE</spring-cloud.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-consul-discovery</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-consul-config</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
2.1? 數(shù)據(jù)提供模塊consul-producer
創(chuàng)建數(shù)據(jù)提供服務(wù)模塊consul-producer,修改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>springcloud-consul</artifactId><groupId>com.test</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>consul-producer</artifactId><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>4.3.1</version></dependency></dependencies></project>
配置文件application.yml文件為:
debug: falsespring.aop.auto: truespring:application:name: data-producercloud:consul:enabled: truehost: localhostport: 8500discovery:enabled: trueregister: true #是否將自身服務(wù)注冊到consul中hostname: 127.0.0.1healthCheckPath: /actuator/health #服務(wù)健康檢查地址healthCheckInterval: 15sserviceName: ${spring.application.name}tags: testinstanceId: ${spring.application.name}-${spring.cloud.client.ip-address}-${server.port} # 服務(wù)id
啟動(dòng)類DataProducerApplication
package com.test;import cn.hutool.core.convert.Convert; import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.util.NetUtil; import cn.hutool.core.util.NumberUtil; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import java.util.Scanner; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException;@EnableDiscoveryClient @SpringBootApplication @EnableAutoConfiguration public class DataProducerApplication {public static void main(String[] args) {int port = 0;int defaultPort = 8080;int time = 5;Future<Integer> future = ThreadUtil.execAsync(() ->{int p = defaultPort;System.out.println(String.format("請于%d秒鐘內(nèi)輸入端口號(hào), 推薦 8080 、 8081 或者 8082,超過%d秒將默認(rèn)使用 %d", time, time, defaultPort));Scanner scanner = new Scanner(System.in);while(true) {String strPort = scanner.nextLine();if(!NumberUtil.isInteger(strPort)) {System.err.println("只能是數(shù)字");} else {p = Convert.toInt(strPort);scanner.close();break;}}return p;});try{port=future.get(time, TimeUnit.SECONDS);}catch (InterruptedException | ExecutionException | TimeoutException e){port = defaultPort;}if(!NetUtil.isUsableLocalPort(port)) {System.err.printf("端口%d被占用了,無法啟動(dòng)%n", port );System.exit(1);}new SpringApplicationBuilder(DataProducerApplication.class).properties("server.port=" + port).run(args);} }
?DataController處理每一個(gè)請求
package com.test.controller;import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;@RestController public class DataController {@RequestMapping("/*")public String get(HttpServletRequest request) {return String.format("實(shí)際響應(yīng)地址:%s", request.getRequestURL().toString());} }
2.2? 數(shù)據(jù)消費(fèi)模塊consul-consumer
使用LoadBalancerClient實(shí)現(xiàn)服務(wù)轉(zhuǎn)發(fā),即將服務(wù)映射到consul-producer服務(wù)
修改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>springcloud-consul</artifactId><groupId>com.test</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>consul-consumer</artifactId><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies></project>
配置文件application.yml
spring:application:name: data-consumercloud:consul:host: 127.0.0.1port: 8500discovery:register: truehostname: 127.0.0.1healthCheckPath: /actuator/health server:port: 8090data-producer: data-producer
啟動(dòng)類DataConsumerApplication
package com.test;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@SpringBootApplication @EnableDiscoveryClient public class DataConsumerApplication {public static void main(String[] args) {SpringApplication.run(DataConsumerApplication.class, args);} }
DataConsumerController處理請求
package com.test.controller;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate;import javax.servlet.http.HttpServletRequest;@RestController public class DataConsumerController {@Value("${data-producer}")private String dataProducer;@Autowiredprivate LoadBalancerClient loadBalancerClient;@RequestMapping("/data-api/**")public String test(HttpServletRequest request) {ServiceInstance serviceInstance = loadBalancerClient.choose(dataProducer);String result = new RestTemplate().getForObject(serviceInstance.getUri().toString() + request.getRequestURI().replace("data-api", ""),String.class);System.out.println(result);return result;} }
2.3 gateway網(wǎng)關(guān)實(shí)現(xiàn)服務(wù)轉(zhuǎn)發(fā)
創(chuàng)建gateway-service模塊,修改pom.xml增加gateway所需依賴
<?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>springcloud-consul</artifactId><groupId>com.test</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>gateway-service</artifactId><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency></dependencies></project>
配置文件application.yml
server:port: 8100spring:application:name: gateway-servicecloud:gateway:routes:- id: data-service1 #請求 http://localhost:8100/data-service1/test會(huì)轉(zhuǎn)發(fā)到data-producer服務(wù),uri: lb://data-producer #在服務(wù)注冊中心找服務(wù)名為 data-producer的服務(wù), predicates:- Path=/data-service1/*filters:- StripPrefix=1- id: data-service2 # 請求 http://localhost:8100/data-service2/test轉(zhuǎn)發(fā)到 http://localhost:8080/testuri: http://localhost:8080predicates:- Path=/data-service2/*filters:- StripPrefix=1 #前綴, 在當(dāng)前路徑匹配中表示去掉第一個(gè)前綴 /data-service2consul:enabled: truehost: localhostport: 8500discovery:enabled: trueregister: false #是否將自身服務(wù)注冊到consul中hostname: 127.0.0.1healthCheckPath: /actuator/health #服務(wù)健康檢查地址healthCheckInterval: 15sserviceName: ${spring.application.name}tags: testinstanceId: ${spring.application.name}-${spring.cloud.client.ip-address}-${server.port} # 服務(wù)id
啟動(dòng)類GatewayServiceApplication
package com.test;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@SpringBootApplication public class GatewayServiceApplication {public static void main(String[] args) {SpringApplication.run(GatewayServiceApplication.class, args);} }
3、測試及項(xiàng)目下載
首先啟動(dòng)consul,啟動(dòng)兩個(gè)DataProducerApplication實(shí)例,端口號(hào)為8080、8081, 啟動(dòng)DataConsumerApplication及GatewayServiceApplication
DataConsumerApplication服務(wù)
在瀏覽器輸入http://localhost:8090/data-api/test, 訪問DataConsumerApplication服務(wù),輸出結(jié)果為: “實(shí)際響應(yīng)地址:http://127.0.0.1:8081/test”? 或? "實(shí)際響應(yīng)地址:http://127.0.0.1:8080/test"
GatewayServiceApplication服務(wù)
轉(zhuǎn)發(fā)格式見application.yml文件
在瀏覽器中輸入http://localhost:8100/data-service1/test, 訪問GatewayServiceApplication同樣 可以看到? 有時(shí)訪問8080端口的DataProducerApplication服務(wù),有時(shí)訪問8081端口的DataProducerApplication服務(wù)
在瀏覽器中輸入http://localhost:8100/data-service2/test, 實(shí)際響應(yīng)的是8080端口的DataProducerApplication服務(wù),
項(xiàng)目下載
?
轉(zhuǎn)載于:https://www.cnblogs.com/wushengwuxi/p/11585567.html
總結(jié)
以上是生活随笔為你收集整理的SpringCloud + Consul服务注册中心 + gateway网关的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 原神珊瑚宫心海圣遗物怎么搭配?
- 下一篇: 强大的Charles的使用,强大的flu