前段时间申请了一个淘宝客的账号,本来想挣点烟钱,结果发现流量上不去,就此作罢。
当时是基于Spring boot开发的,正好最近想用Spring cloud搭个环境,所以打算代码拿出来,给各位JRS看看。
系统架构图
下面介绍以下相关的组件:
淘宝客客户端:是一个web系统,整个系统的访问入口,通过http调用服务端的接口,实现restful风格api
网关Zuul:api-gateway网关,提供路由控制、负载均衡,甚至服务降级的功能
淘宝客Service:只实现了一个,不过可以启动多个实例;提供服务给客户端调用
注册中心Eureka:对以上各个服务进行治理,即注册、发现客户端、网关、service、配置中心等;图示A,B,C,三个注册中心是为了实现注册中心的高可用,可以采用的时两两注册的方式
配置中心Config:一般系统可能有开发dev、测试test、生成prod,spring cloud用的是建立多个配置文件的方式实现管理的,系统的配置文件可以通过git来管理
这里先附上Spring cloud的demo代码:https://github.com/kobet/proxy,下篇文章会详细介绍各个应用关系及运行方式
后面也会传上集成了淘宝客的代码工程
下面看一下代码结构及运行效果
1.启动注册中心:proxy-eureka-server
2.相继启动服务端proxy-service-a,proxy-service-b,网关proxy-api-gateway,服务消费端proxy-compute-service
3.访问注册中心,检查各个服务是否注册成功:http://localhost:1111/
发现已经成功注册了。
4.试着访问以下地址:http://localhost:4444/add?a=1&b=200,如果计算成功,那么说明程序跑起来了
看一下客户端代码
public class ConsumerController {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(@RequestParam("a") Integer a, @RequestParam("b") Integer b) {
return restTemplate.getForEntity("http://proxy-api-gateway/api-a/add?a=" + a + "&b=" + b, String.class).getBody();
}
}
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(@RequestParam("a") Integer a, @RequestParam("b") Integer b) {
return restTemplate.getForEntity("http://proxy-api-gateway/api-a/add?a=" + a + "&b=" + b, String.class).getBody();
}
}
可以发现是直接调用的网关的服务名,其中restTemplate是用rest风格访问接口的,再看一下网关的配置文件
#服务名
spring.application.name=proxy-api-gateway
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
#以下是路由规则
#zuul.routes.api-a-url.path=/api-a/**
#zuul.routes.api-a-url.url=http://localhost:2222/
#zuul.routes.api-b-url.path=/api-b/**
#zuul.routes.api-b-url.url=http://localhost:3333/
zuul.routes.api-a-url.path=/api-a/**
zuul.routes.api-a-url.url=proxy-service-a
zuul.routes.api-b-url.path=/api-b/**
zuul.routes.api-b-url.url=proxy-service-b
可以发现配置的服务名就是
proxy-api-gateway
这就是因为注册发现之后,直接访问服务而不用指定IP,而后面配置就是相关的路由规则