根据7001搭建7002,重点在于改yml
找到c:Windowssystem32driversetc路径下的hosts文件
添加以下内容:
127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com
127.0.0.1 eureka7003.com
127.0.0.1 myzuul.com
127.0.0.1 config-3344.com
127.0.0.1 client-config.com
127.0.0.1 cloud-provider-payment
修改7001的yml:
server:
port: 7001
eureka:
instance:
hostname: eureka7001.com
client:
# 不会自己注册自己
register-with-eureka: false
# 不需要检索服务,我自己就是服务中心
fetch-registry: false
service-url:
# 交互地址依赖于这个地址
defaultZone: http://eureka7002.com:7002/eureka/
7002同样如此修改
localhost:7001和localhost:7002都可以访问
http://eureka7001.com:7001/和http://eureka7002.com:7002/ 都可以正常访问
互相注册成功
接着对订单(80)和支付(8001)模块进行注册
进入yml中,将defaultZone改成以下内容:
defaultZone:http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
项目启动顺序:
服务→服务提供者→服务消费者
http://localhost/consumer/payment/get/1 显示正常即可
除了服务集群外,服务提供者也需要集群
所以新建payment8002,对照8001复制粘贴
两个payment对外暴露的名字为cloud-payment-service
在controller中加入:
@Value("${server.port}")
private String serverPort;
注意,这个注解是org.springframework.beans.factory.annotation.Value;
不是lombok的
修改部分内容:
return new CommonResult(200,"插入成功,端口号为:"+serverPort,result);
return new CommonResult(200,"查询成功,端口号为:"+serverPort,payment);
以判断是哪个服务提供方提供的服务
再次重启项目,输入http://eureka7002.com:7002/,可看到成功页面
http://localhost:8002/payment/get/1
http://localhost:8001/payment/get/1
无问题
http://localhost/consumer/payment/get/1
反复刷新发现服务提供方一直是8001,因为消费者的controller写死了8001
public static final String PAYMENT_URL="http://localhost:8001";
改成
public static final String PAYMENT_URL="http:// CLOUD-PAYMENT-SERVICE";
即微服务名称
改掉后再访问服务就会发现出现错误,识别不了主机,这时候就需要加上负载均衡的注解
com/xs/springcloud/config/ApplicationContextConfig.java中getRestTemplate()方法上加上@LoadBalanced即可
再访问http://localhost/consumer/payment/get/1 就会发现端口号一直在变了
以上为20-22集的内容



