从b站学习springcloud,现在进行总结,该总结除去了视频中出现的小错误,对有些易错的地方进行了提醒
b站链接:https://www.bilibili.com/video/av55304977
资料链接:
https://pan.baidu.com/s/1o0Aju3IydKA15Vo1pP4z5w
提取码: 21ru
上一节链接:https://blog.csdn.net/qq_40893824/article/details/103327911
下一节链接:https://blog.csdn.net/qq_40893824/article/details/103332281
下面的内容总结:子工程→pom→application→启动类→修改eurekaclient中StudentHandler→测试
实现细节:
1.创建module模块,命名为zuul
2.该模块的pom文件,添加代码:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
</dependencies>
3.在resource下创application.yml,添加代码:
server:
port: 8030
spring:
application:
name: gateway
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
zuul:
routes:
provider: /p/**
# /p/**:通过p映射到provider =http://localhost:8010/
4.在java中创包com.southwind,在southwind中创启动类ZuulApplication.java,填入代码:
package com.southwind;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@EnableZuulProxy
@EnableAutoConfiguration
//@EnableZuulProxy:包含了 @EnableZuulServer,设置该类是网关的启动类。
//@EnableAutoConfiguration:
//可以帮助SpringBoot应用将所有符合条件的@Configuration配置加载到当前SpringBoot创建并使用的IoC容器中。
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class,args);
}
}
5.zuul模块的处理到此为止
先检查zuul是否可以调通eurekaclient的服务
启动eurekaserver、eurekaclient、zuul的启动类
进入http://localhost:8761
说明服务端和zuul已经注册成功
a.查 http://localhost:8030/p/student/findAll
查 http://localhost:8030/p/student/findById/2
进入postman
a.增 post→ http://localhost:8030/p/student/save
查 get→ http://localhost:8030/p/student/findAll
b.改 post→ http://localhost:8030/p/student/update
查 get→ http://localhost:8030/p/student/findAll
6.测试zuul的负载均衡功能:现在去eurekaclient中修改StudentHandler中的代码(其实是添加代码,源代码不变)
添加代码:
@Value("${server.port}")
private String port;
@GetMapping("/index")
public String index(){
return "当前端口:"+this.port;
}
7.在southwind中在复制一份ProviderApplication.java,但命名为ProviderApplication2.java
先启动ZuulApplication.java(其实它的端口是8010),
启动好了后,修改application.yml中8010为8011,再启动ZuulApplication2.java
再看http://localhost:8761中:
可见provider有两个端口
进入 http://localhost:8030/p/student/index
其端口是8010,刷新一下:
端口变为8011,也就是每次刷新,其端口都会变!
end
上一节链接:https://blog.csdn.net/qq_40893824/article/details/103327911
下一节链接:https://blog.csdn.net/qq_40893824/article/details/103332281