1
概述
从之前的配置里面我们可以看到我们的 URL 都是写死的,这不符合我们微服务的要求,我们微服务是只要知道服务的名字,根据名字去找,而直接写死就没有负载均衡的效果了
默认情况下
Gateway 会根据注册中心的服务列表,以注册中心上微服务名为路径创建动态路
由进行转发,从而实现动态路由的功能。
需要注意的是 uri 的协议为 lb(
load Balance
),表示启用 Gateway 的负载均衡功能。
lb://serviceName 是 spring cloud gateway 在微服务中自动为我们创建的负载均衡 uri
协议:就是双方约定的一个接头暗号
http
:
//
项目实例
1.gateway-server模块
1.1.pom.xml文件
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
1.2.application.yml文件
server:
port: 80
spring:
application:
name: gateway-server
cloud:
gateway:
enabled: true
discovery:
locator:
enabled: true #开启动态路由 开启通过应用名称找到服务的功能
lower-case-service-id: true #开启服务名称小写
eureka:
client:
service-url:
defaultZone: http://192.168.174.133:8761/eureka
registry-fetch-interval-seconds: 3
instance:
hostname: localhost
instance-id: ${eureka.instance.hostname}:${spring.application.name}:${server.port}
1.3主函数类
package com.it;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class GatewayServerApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayServerApplication.class, args);
}
}
2.login-service模块
2.1.pom.xml文件
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
2.2.application.yml文件
server:
port: 8081
spring:
application:
name: login-service
eureka:
client:
service-url:
defaultZone: http://192.168.174.133:8761/eureka
registry-fetch-interval-seconds: 3
instance:
hostname: localhost
instance-id: ${eureka.instance.hostname}:${spring.application.name}:${server.port}
2.3.LoginController文件
package com.it.controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.UUID;
public class LoginController {
@GetMapping("doLogin")
public String doLogin(String name,String pwd){
System.out.println(name);
System.out.println(pwd);
String s = UUID.randomUUID().toString();
return s;
}
}
2.4主函数类
package com.it;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class LoginServiceApplication {
public static void main(String[] args) {
SpringApplication.run(LoginServiceApplication.class, args);
}
}
3.功能测试
启动动态路由后,访问路径时需要在localhost后面加上,要访问服务的名称,后面再跟上这个服务中的方法接口名
如果不加服务名称,还是按照以前的方法写,会导致访问报404
好文推荐
发表评论