老规矩,建几个项目:
Eureka服务器(zuul-eureka-server),端口8761;
服务提供者(zuul-book-service),端口9000,提供/book/{bookld}服务,用于查找图书,一下是配置和部分代码;
server:
port: 9000
spring:
application:
name: zuul-book-service
eureka:
instance:
hostname: localhost
client:
service-url:
defaultZone: http://localhost:8761/eureka/
@RestController
public class MainController {
@GetMapping("/book/{id}")
public String book(@PathVariable("id") Integer id) {
return "book:" + id;
}
}
服务调用者(zuul-sale-service),端口9100,对外发布销售服务/sale-book/{bookld},在该服务中会调用 zuul-book-service 来查找Book;
添加以下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
server:
port: 9100
spring:
application:
name: zuul-sale-service
eureka:
instance:
hostname: localhost
client:
service-url:
defaultZone: http://localhost:8761/eureka/
发布服务
@FeignClient("zuul-book-service")
public interface BookService {
@GetMapping("/book/{id}")
String getBook(@PathVariable("id") Integer id);
}
@RestController
public class SaleController {
@Autowired
private BookService bookService;
@GetMapping("/sale-book/{id}")
public String saleBook(@PathVariable("id") Integer id) {
String s = bookService.getBook(id);
return "this is "+s;
}
}
再建个项目(zuul-gateway)
加入以下依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
启动类加上@EnableZuulProxy注解,端口8080,以下是配置
server:
port: 8080
spring:
application:
name: zuul-gateway
eureka:
instance:
hostname: localhost
client:
service-url:
defaultZone: http://localhost:8761/eureka/
zuul:
routes:
sale:
#ignoredPatterns: /sale/noRoute
path: /sale/**
serviceId: zuul-sale-service
声明所有的/sale/**请求将会被转发到Id为zuul-sale-service的服务进行处理。
还可添加ignoredPatterns来设置不进行路由的URL
一般情况下,配置了 serviceId 后,在处理请求的 routing 阶段,将会使用一个名称为RibbonRoutingFilte的过滤器,该过滤器会调用Ribbon的API来实现负载均衡, 默认情况下用 HttpClient来调用集群服务。
依次启动集群,在浏览器中访问http://localhost/sale/sale-book/1,正常显示就ok。
以下是结构图
照着书每天敲一点吧哈哈哈哈哈哈哈哈