spring cloud 中zuul的简单使用
创建4个微服务项目
zuul eureka demo_a demo_b
zuul:
启动类添加 : @EnableZuulProxy注解
@SpringBootApplication
@EnableZuulProxy
public class ZuulDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulDemoApplication.class, args);
}
}
配置文件 :application.properties
spring.application.name=api-gateway
server.port=5555
# routes to serviceId 这里边是通过serviceid来绑定地址,当在路径后添加/api-a/ 则是访问service-A对应的服务。
zuul.routes.api-a.path=/api-a/**
zuul.routes.api-a.serviceId=service-A
zuul.routes.api-b.path=/api-b/**
zuul.routes.api-b.serviceId=service-B
# routes to url 这里是绑定具体的ip地址
zuul.routes.api-a-url.path=/api-a-url/**
zuul.routes.api-a-url.url=http://localhost:2222/
# routes to url 这里是绑定具体的ip地址
zuul.routes.api-b-url.path=/api-b-url/**
zuul.routes.api-b-url.url=http://localhost:3333/
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
pom文件
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
org.springframework.cloud
spring-cloud-starter-netflix-zuul
实例 :访问 (zuul的服务) http://127.0.0.1:5555/api-b/b/hello 实际上会访问 http://127.0.0.1:3333/b/hello (我的demo_b项目的端口是3333)
eureka:
启动类 添加 @EnableEurekaServer
@EnableEurekaServer
@SpringBootApplication
public class EurekaDemoApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaDemoApplication.class, args);
}
}
配置文件 application.properties
server.port=1111
#eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/
pom
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
项目a:
启动文件:
@SpringBootApplication
@EnableDiscoveryClient
public class AaaaApplication {
public static void main(String[] args) {
SpringApplication.run(AaaaApplication.class, args);
}
}
配置文件:application.properties
spring.application.name=service-A
server.port=2222
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
pom
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
测试controller
@Controller
@RequestMapping("/a")
public class Aacontroller {
@RequestMapping("/hello")
@ResponseBody
public String test(){
return "hello:A";
}
}
demo_b : bbbb
和上面的a项目一样
controller不一样
@Controller
@RequestMapping("/b")
public class BbController {
@RequestMapping("/hello")
@ResponseBody
public String test(){
return "hello:B";
}
}
以上OK了
最终效果是 访问
http://127.0.0.1:5555/api-a/a/hello 出现 hello:A (/a/hello)
http://127.0.0.1:5555/api-b/b/hello 出现 hello:B (b/hello)
end…
代码下载 :
链接: https://pan.baidu.com/s/1-N7r_HS2gfWkdxlzU4Cf3g
提取码: 869x