2. Readme-zh_CN.md

2. Readme-zh_CN.md,第1张

[图片上传失败...(image-47bff3-1555426723726)]

[图片上传失败...(image-23a1a9-1555426723726)]

[图片上传失败...(image-a9f209-1555426723726)]

[图片上传失败...(image-16fb99-1555426723726)]

个人财务的简易解决方案

This is a proof-of-concept application , which demonstrates Microservice Architecture Pattern using Spring Boot, Spring Cloud and Docker。

With a pretty neat user interface, by the way。

[图片上传失败...(image-49ef69-1555426723726)]

[图片上传失败...(image-984dbb-1555426723726)]

PiggyMetrics 分解为三个核心微服务。 全部都是独立可部署应用, 根据各自的业务域进行编排。

<img width="880" alt="Functional services" src="https://cloud。githubusercontent。com/assets/6069066/13900465/730f2922-ee20-11e5-8df0-e7b51c668847。png">

涵盖了通用用户登录逻辑以及验证: 收入/支持 项目, 储蓄以及账户设置。

对每个账号的差升宏主要统计数据进行计算,并为捕获时序。 ( 不知道咋翻译 译者注 ) 数据点包含值,标准化为基础货币和时间段笑冲。此数据用于跟踪帐户生命周期中的现金流动态。

存储了用户通讯录信息以及通知设置 (譬如提醒和备份频率)。

定时任务从其他服务收集了需要的信息以及发送邮件消息到订阅用户。

分布式系统中有许多常见的模式,可以帮助我们使所描述的核心服务工作起来。[Spring Cloud]( http://projects.spring.io/spring-cloud/ )提供了增强Spring引导应用程序行为以实现这些模式的强大工具。我将简要介绍它们。

<img width="880" alt="Infrastructure services" src="https://cloud。githubusercontent。com/assets/6069066/13906840/365c0d94-eefa-11e5-90ad-9d74804ca412。png">

Spring Cloud Config 是用于分布式系统的水平可扩展的集中配置服务。它使用可插入虚册的存储库层,当前支持本地存储、Git和Subversion。

在这个项目中,我使用 native profile , 它只从本地类路径加载配置文件。 你可以在 Config service resources 看到 shared 目录。

现在,当通知服务请求其配置时,使用 shared/notification-service。yml 和 shared/application。yml (在所有客户端应用程序之间共享)。

只需只用 spring-cloud-starter-config 依赖, 自动配置就可以完成剩下的了。

现在,您不需要在应用程序中嵌入任何属性。 只需要提供 bootstrap.yml 应用名和配置中心地址:

例如, [EmailService bean]( https://github.com/jinweibin/PiggyMetrics/blob/master/notification-service/src/main/java/com

/piggymetrics/notification/service/EmailServiceImpl.java) 使用 @RefreshScope 注解。

这就意味着不需要重启以及重新编译的情况就可以通知应用服务变更电子邮件内容和副标题。

首先将配置中心修改参数,然后,发送刷新请求以通知服务参数更新:

curl -H "Authorization: Bearer #token#" -XPOST http://127.0.0.1:8000/notifications/refresh

另外, 你也可以使用 Git 的 Webhooks webhooks to automate this process

鉴权任务被分摊到各个微服务上,那些被 OAuth2 tokens 授权的后台服务资源。

Auth Server is used for user authorization as well as for secure machine-to-machine communication inside a perimeter。

鉴权服务器用于用户鉴权,也用于在外围环境中进行安全的机器到机器通信。。

这个项目用户鉴权方式使用的是 Password credentials 授权方式

(因为他只给本地Piggmetrics用户界面使用) ,另外微服务的授权使用 Client Credentials 授权。

Spring Cloud Security 提供了方便的注解以及自动配置使应用能够更加简单的实现服务端以及客户端的鉴权 。

在这里你可以学到更多 文档 也可以在 Auth Server code 确认详细配置。

对于客户端, 所有的鉴权工作都和原来基于 session 的鉴权方式一样, 你可以在 request 中获取 Principal 对象, 基于表达式和 @PreAuthorize 注解去验证用户的角色或者其他内容

每个PiggyMetrics的客户端(账户服务,统计服务,通知服务和浏览器)后端服务都拥有 server 作用域,浏览器则拥有 ui 。

所以我们也可以保护控制器不受外部访问的影响, 例如:

如你所见, 这边有3个核心服务,他们向其他的客户端暴露外部API接口。

在真实系统中,这个数字会随着系统的复杂性增长得非常之快。

事实上, 为了渲染一个复杂的网页可能要触发上百上千个服务。

理论上, 客户端可以直接发送请求到各个微服务供应商去。

但是很明显的问题是, 这个 *** 作会有很大的挑战以及限制, 像是必须知道所有节点的地址, 分别对每一条信息执行HTTP请求, 然后在一个客户端去合并结果。

另一个问题是后端可能使用的是非Web友好协议。

通常来说, 使用 API 网关可能是一个更好的方法。

It is a single entry point into the system, used to handle requests by routing them to the appropriate backend service or by invoking multiple backend services and aggregating the results 。

这样进入系统就只有一个入口, 可以通过将请求路由到适合的后端服务或者多个好多服务 aggregating the results 。

此外,它还可以用于身份验证、监控、压力和金丝雀测试、服务迁移、静态响应处理、主动流量管理。

Netflix 开源了 这样的边缘服务 ,

现在我们就可以使用 Spring Cloud 的 @EnableZuulProxy 注解去开启它。

In this project, I use Zuul to store static content (ui application) and to route requests to appropriate

这个项目里, 我使用了 Zuul 去存储静态资源内容 ( 用户界面应用 ) 还有去路由请求到合适的微服务去。

Here's a simple prefix-based routing configuration for Notification service:

这里是一个简单的基于前缀的通知服务的路由配置:

以上配置以为着所有以 /notifications 开头的请求都会被路由到通知服务去。

这边没有往常的硬编码的地址。 Zuul 使用了 服务发现

机制去定位通知服务的所有实例然后 [负载均衡]( https://github.com/jinweibin/PiggyMetrics/blob/master/README

.md#http-client-load-balancer-and-circuit-breaker)。

另一种常见的架构模式是服务发现。

这可以自动检测到服务实例的网络位置,

它可以根据服务的故障,升级或者是自动伸缩来动态的分配地址。

服务发现的关键就是注册中心。

这个项目使用了Netflix Eureka 作为服务的注册中心。

Eureka is a good example of the client-side discovery pattern,

Eureka 是一个很好的客户端发现模式的例子,

when client is responsible for determining locations of available service instances (using Registry server) and load balancing requests across them。

With Spring Boot, you can easily build Eureka Registry with spring-cloud-starter-eureka-server dependency, @EnableEurekaServer annotation and simple configuration properties。

Client support enabled with @EnableDiscoveryClient annotation an bootstrap。yml with application name:

Now, on application startup, it will register with Eureka Server and provide meta-data, such as host and port, health indicator URL, home page etc。 Eureka receives heartbeat messages from each instance belonging to a service。 If the heartbeat fails over a configurable timetable, the instance will be removed from the registry。

Also, Eureka provides a simple interface, where you can track running services and a number of available instances: http://localhost:8761

Netflix OSS provides another great set of tools。

Ribbon is a client side load balancer which gives you a lot of control over the behaviour of HTTP and TCP clients。 Compared to a traditional load balancer, there is no need in additional hop for every over-the-wire invocation - you can contact desired service directly。

Out of the box, it natively integrates with Spring Cloud and Service Discovery。 Eureka Client provides a dynamic list of available servers so Ribbon could balance between them。

Hystrix is the implementation of Circuit Breaker pattern , which gives a control over latency and failure from dependencies accessed over the network。 The main idea is to stop cascading failures in a distributed environment with a large number of microservices。 That helps to fail fast and recover as soon as possible - important aspects of fault-tolerant systems that self-heal。

Besides circuit breaker control, with Hystrix you can add a fallback method that will be called to obtain a default value in case the main command fails。

Moreover, Hystrix generates metrics on execution outcomes and latency for each command, that we can use to monitor system behavior 。

Feign is a declarative Http client, which seamlessly integrates with Ribbon and Hystrix。 Actually, with one spring-cloud-starter-feign dependency and @EnableFeignClients annotation you have a full set of Load balancer, Circuit breaker and Http client with sensible ready-to-go default configuration。

Here is an example from Account Service:

In this project configuration, each microservice with Hystrix on board pushes metrics to Turbine via Spring Cloud Bus (with AMQP broker)。 The Monitoring project is just a small Spring boot application with Turbine and Hystrix Dashboard 。

See below how to get it up and running 。

Let's see our system behavior under load: Account service calls Statistics service and it responses with a vary imitation delay。 Response timeout threshold is set to 1 second。

<img width="880" src="https://cloud。githubusercontent。com/assets/6069066/14194375/d9a2dd80-f7be-11e5-8bcc-9a2fce753cfe。png">

Centralized logging can be very useful when attempting to identify problems in a distributed environment。 Elasticsearch, Logstash and Kibana stack lets you search and analyze your logs, utilization and network activity data with ease。

Ready-to-go Docker configuration described in my other project 。

Analyzing problems in distributed systems can be difficult, for example, tracing requests that propagate from one microservice to another。 It can be quite a challenge to try to find out how a request travels through the system, especially if you don't have any insight into the implementation of a microservice。 Even when there is logging, it is hard to tell which action correlates to a single request。

Spring Cloud Sleuth solves this problem by providing support for distributed tracing。 It adds two types of IDs to the logging: traceId and spanId。 The spanId represents a basic unit of work, for example sending an HTTP request。 The traceId contains a set of spans forming a tree-like structure。 For example, with a distributed big-data store, a trace might be formed by a PUT request。 Using traceId and spanId for each operation we know when and where our application is as it processes a request, making reading our logs much easier。

The logs are as follows, notice the [appname,traceId,spanId,exportable] entries from the Slf4J MDC:

An advanced security configuration is beyond the scope of this proof-of-concept project。 For a more realistic simulation of a real system, consider to use https, JCE keystore to encrypt Microservices passwords and Config server properties content (see documentation for details)。

Deploying microservices, with their interdependence, is much more complex process than deploying monolithic application。 It is important to have fully automated infrastructure。 We can achieve following benefits with Continuous Delivery approach:

Here is a simple Continuous Delivery workflow, implemented in this project:

<img width="880" src="https://cloud。githubusercontent。com/assets/6069066/14159789/0dd7a7ce-f6e9-11e5-9fbb-a7fe0f4431e3。png">

In this configuration , Travis CI builds tagged images for each successful git push。 So, there are always latest image for each microservice on Docker Hub and older images, tagged with git commit hash。 It's easy to deploy any of them and quickly rollback, if needed。

Keep in mind, that you are going to start 8 Spring Boot applications, 4 MongoDB instances and RabbitMq。 Make sure you have 4 Gb RAM available on your machine。 You can always run just vital services though: Gateway, Registry, Config, Auth Service and Account Service。

In this mode, all latest images will be pulled from Docker Hub。

Just copy docker-compose。yml and hit docker-compose up

If you'd like to build images yourself (with some changes in the code, for example), you have to clone all repository and build artifacts with maven。 Then, run docker-compose -f docker-compose。yml -f docker-compose。dev。yml up

docker-compose。dev。yml inherits docker-compose。yml with additional possibility to build images locally and expose all containers ports for convenient development。

All Spring Boot applications require already running Config Server for startup。 But we can start all containers simultaneously because of depends_on docker-compose option。

Also, Service Discovery mechanism needs some time after all applications startup。 Any service is not available for discovery by clients until the instance, the Eureka server and the client all have the same metadata in their local cache, so it could take 3 heartbeats。 Default heartbeat period is 30 seconds。

PiggyMetrics is open source, and would greatly appreciate your help。 Feel free to suggest and implement improvements。

zuul路由的几个配置参数

1.静态路由

zuul:

routes:

myroute1:

path: /mypath/**

url: http://localhost:8080 (注意这里url要http://开头)

2.静态路由+ribbon负载均衡/故障切换

zuul:

routes:

myroutes1:

path: /mypath/**

serviceId: myserverId

myserverId:

ribbon:

listOfServers: localhost:8080, localhost:8081

ribbon:

eureka:

enabled: false

3.动态路由+ribbon负载均衡/故障切换

zuul:

routes:

myroutes1:

path: /mypath/**

serviceId: myserviceId

eureka:

client:

serviceUrl:

defaultZne:xxx

4.路由匹配的一些配置

stripPrefix=true,转发会过滤掉前缀。

path: /myusers/**,默认时转发到服务的请求是/**,如果stripPrefix=false,转发的请求是/myusers/**

zuul.prefix=/api 会对所有的运亮局path增加一个/api前缀

ignoredPatterns: /**/admin/** 过滤掉匹配的url

route:

users: /myusers/** 会匹配所有/myusers/**的url,但由于ignoredPatterns, /myusers/**/admin/**的请求不会被转发,而是直接由zuul里的接口接收

匹配顺序

path:/myusers/**

path:/** 如果是在application.yml中配置的,那么会优先匹配/myusers/**

但如果是applicaiton.properties配置的,那么可能导致/myusers/**被/**覆盖

ignored-Services: ‘*‘ 对于自动发现的services,除了route中明确指定的,其他都会被忽略

5.请求头过滤

route.sensitiveHeaders: Cookie,Set-Cookie,Authorization

默认就有这三个请求头,意思是不向下游转发请求这几个头

zuul.ignoredHeaders 是一个全局设置,而route.sensitiveHeaders是局部设键判置

zuul过滤器

标准的zuul过滤器有4中,分别对应一次路由转发的几个关键旁让点

pre: 在路由转发之前起作用

routing: 在路由时其作用

post: 在把结果返回给浏览器时起作用

error: 在整个路由阶段,出现异常时起作用

如果要分析前端传来的参数,验证前端身份等对前端参数的 *** 作,显然是用pre过滤器

如果是要对返回给前端的结果进行 *** 作或者分析,显然是用post过滤器

编写自定义路由器

public class MyFilter extends ZuulFilter{

filterType()重写,返回这个过滤器的类型

filterOrder()重写,返回这个过滤器在过滤器链的顺序

shouldFilter() true启动

run()具体逻辑

}

Netflix Eureka是Spring Cloud服务注册发现的基础组件

Eureka提供RESTful风格(HTTP协议)的服务注册与发现

Eureka采用C/S架构,Spring Cloud内置客户端

启用应用,访问 http://localhost:8761

Eureka客户端开发要点

maven依赖spring-cloud-starter-netflix-eureka-client application.yml

配置eureka.client.service-url.defaultZone

入口类增加@EnableEurekaClient

先启动注册中心,在启动客户端,访问 localhost:8761查看eureka注册中心,看到客户端注册

Eureka名词概念

Register - 服务注册, 向Eureka进行注册登辩陵册记

Renew - 服务续约,30秒/次心跳包健康检查.90秒未收到剔除服务

Fetch Registries - 获取服务注册列表,获取其他微服务地址

Cancel - 服务下线, 某个微服务通知注册中心汪罩暂停服务

Eviction - 服务剔除,90秒未续约,从服务注册表进行剔除

Eureka自我保护机制

Eureka在运行期去统计心跳失败率在15分钟之内是否低于 85%

如果低于 85%,会将这些实例保护起来,让这些实例不会被剔除

关闭自我保护:eureka.服务实例.

enable-self-preservation: false

PS: 如非网络特别不稳定,建议关闭

Eureka高可用配置步骤

服务提供者defaultZone指向其他的Eureka

客户端添加所有Eureka 服务实例 URL

Actuator自动为微服务创建一系列的用于监控的端点

Actuator在SpringBoot自带,SpringCloud进行扩展

pom.xml依赖spring-boot-starter-actuator

RestTemplate + @LoadBalanced 显式调用

OpenFeign 隐藏微服务间通信细节

Ribbon是RestTemplate与OpenFeign的通信基础

Feign是一个开源声明式WebService客户端,用于简携宏化服务通信

Feign采用“接口+注解”方式开发,屏蔽了网络通信的细节

OpenFeign是SpringCloud对Feign的增强,支持Spring MVC注解

1.新建Spring boot Web项目,application name 为 product-service

在pom.xml中引入依赖

spring-cloud-starter-alibaba-nacos-discovery作用为向Nacos server注册服务。

spring-cloud-starter-openfeign作用为实现服务调用。

2.修改application.yml配置文件

3.在启动类上添加@EnableDiscoveryClient、@EnableFeignClients注解

4.编写OrderClient Interface

注:/api/v1/order/test 会在下面order-service声明。

OrderClient.java

5.编写Controller和service

ProductController.java

ProductService.java

1.OpenFeign开启通信日志

基于SpringBoot的logback输出,默认debug级别

设置项:feign.client.config.微服务id.loggerLevel

微服务id:default代表全局默认配置

2.通信日志输出格式

NONE: 不输出任何通信日志

BASIC: 只包含URL、请求方法、状态码、执行时间

HEADERS:在BASIC基础上,额外包含请求与响应头

FULL:包含请求与响应内容最完整的信息

3.OpenFeign日志配置项

LoggerLevel开启通信日志

ConnectionTimeout与ReadTimeout

利用httpclient或okhttp发送请求

1.OpenFeign通信组件

OpenFeign基于JDK原生URLConnection提供Http通信

OpenFeign支持Apache HttpClient与Square OkHttp

SpringCloud按条件自动加载应用通信组件

2.应用条件

Maven引入feign-okhttp或者feign-httpclient依赖

设置feign.[httpclient|okhttp].enabled=true

POST方式传递对象使用@RequestBody注解描述参数

GET方式将对象转换为Map后利用@RequestParam注解描述

雪崩效应:服务雪崩效应产生与服务堆积在同一个线程池中,因为所有的请求都是同一个线程池进行处理,这时候如果在高并发情况下,所有的请求全部访问同一个接口,这时候可能会导致其他服务没有线程进行接受请求,这就是服务雪崩效应效应。

服务熔断:熔断机制目的为了保护服务,在高并发的情况下,如果请求达到一定极限(可以自己设置阔值)如果流量超出了设置阈值,让后直接拒绝访问,保护当前服务。使用服务降级方式返回一个友好提示,服务熔断和服务降级一起使用。

1.Hystrix熔断器

Hystrix(豪猪)是Netflix开源的熔断器组件,用于为微服务提供熔断机制预防雪崩,保护整体微服务架构的健康

2.Hystrix功能

预防微服务由于故障,请求长时间等待导致Web容器线程崩溃

提供故障备选方案,通过回退(fallback)机制提供”服务降级”

提供监控仪表盘,实时监控运行状态

3.Hystrix 熔断器工作原理

服务的健康状况 = 请求失败数 / 请求总数.

熔断器开关由关闭到打开的状态转换是通过当前服务健康状况和设定阈值比较决定的.

当熔断器开关关闭时, 请求被允许通过熔断器. 如果当前健康状况高于设定阈值, 开关继续保持关闭. 如果当前健康状况低于

设定阈值, 开关则切换为打开状态.

当熔断器开关打开时, 请求被禁止通过.

当熔断器开关处于打开状态, 经过一段时间后, 熔断器会自动进入半开状态, 这时熔断器只允许一个请求通过. 当该请求调用

成功时, 熔断器恢复到关闭状态. 若该请求失败, 熔断器继续保持打开状态, 接下来的请求被禁止通过.

熔断器的开关能保证服务调用者在调用异常服务时, 快速返回结果, 避免大量的同步等待. 并且熔断器能在一段时间后继续侦测请求执行结果, 提供恢复服务调用的可能.

4.什么情况下会触发服务降级

FAILURE: 执行失败,抛出异常

TIMEOUT:执行超时(默认1秒)

SHORT_CIRCUITED:熔断器状态为Open

THREAD_POOL_REJECTED:线程池拒绝

SEMAPHORE_REJECTED:信号量拒绝

5.使用Hystrix步骤

1.引入pom文件依赖

6.OpenFeign与Hystrix整合

OpenFeign中使用Hystrix

OpenFeign内置Hystrix,feign.hystrix.enable开启即可

feign: hystrix: enabled: true

在@FeignClient增加fallback属性说明Fallback类

@FeignClient(name="message-service",fallback = MessageServiceFallback.class) public interface MessageService { @GetMapping("/sendsms") public CallbackResult sendSMS(@RequestParam("mobile") String mobile , @RequestParam("message") String message)}

Fallback类要实现相同接口,重写服务降级业务逻辑

@Component public class MessageServiceFallback implements MessageService { @Override public CallbackResult sendSMS(String mobile, String message) { return new CallbackResult("INVALID_SERVICE","消息服务暂时无法使用,短信发送失败")} }

7.Hystrix超时设置

8.部署Hystrix Dashboard监控

Hystrix Client依赖hystrix-metrics-event-stream

Hystrix Client注册HystrixMetricsStreamServlet

监控微服务依赖spring-cloud-starter-netflix-hystrix-dashboard

监控微服务利用@EnableHystrixDashboard开启仪表盘

9.Hystrix熔断设置

产生熔断的条件:

当一个Rolling Window(滑动窗口)的时间内(默认:10秒),最近20次调用请求,请求错误率超过50%,则触发熔断5秒,期间快速失败。

TIPS: 如10秒内未累计到20次,则不会触发熔断

Hystrix熔断设置项:

统一访问出入口,微服务对前台透明

安全、过滤、流控等API管理功能

易于监控、方便管理

Netflix Zuul

Spring Cloud Gateway

Zuul 是Netflix开源的一个API网关, 核心实现是Servlet

Spring Cloud内置Zuul 1.x

Zuul 1.x 核心实现是Servlet,采用同步方式通信

Zuul 2.x 基于Netty Server,提供异步通信

认证和安全

性能监测

动态路由

负载卸载

静态资源处理

压力测试

Spring Cloud Gateway,是Spring“亲儿子”

Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式

Gateway基于Spring 5.0与Spring WebFlux开发,采用Reactor响应式设计

1.使用三部曲

依赖spring-cloud-starter-netflix-zuul

入口增加 @EnableZuulProxy

application.yml 增加微服务映射

2.微服务映射

Spring Cloud Zuul内置Hystrix

服务降级实现接口:FallbackProvider

1.微服务网关流量控制

微服务网关是应用入口,必须对入口流量进行控制

RateLimit是Spring Cloud Zuul的限流组件

https://github.com/marcosbarbero/spring-cloud-zuul-ratelimit

RateLimit采用“令牌桶”算法实现限流

2.什么是令牌桶

1.Zuul的执行过程

2.Http请求生命周期

1.需要实现ZuulFilter接口

shouldFilter() - 是否启用该过滤器

filterOrder() - 设置过滤器执行次序

filterType() - 过滤器类型:pre|routing|post

run() - 过滤逻辑

2.Zuul内置过滤器

3.Zuul+JWT跨域身份验证

1.Spring Cloud Config

2.携程 Apollo

3.阿里巴巴Nacos

1.依赖"spring-cloud-starter-config"

2.删除application.yml,新建bootstrap.yml

3.配置"配置中心"服务地址与环境信息

1、微服务依赖"spring-boot-starter-actuator"

2、动态刷新类上增加@RefreshScope注解

3、通过/actuator/refresh刷新配置

1、通过加入重试机制、提高应用启动的可靠性

2、重试触发条件1:配置中心无法与仓库正常通信

3、重试触发条件2:微服务无法配置中心正常通信


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12232218.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-22
下一篇 2023-05-22

发表评论

登录后才能评论

评论列表(0条)

保存