微服务 1 springboot

1.介绍microservice

2.介绍springboot

3.创建协作的微服务

4.docker部署微服务

5.添加api描述,openapi/swagger

6.添加持久层

7.reactive microservice

构建 scalable, resilient and manageable microservice

问题:

  • How I learned about microservices and what experience I have of their benefits and challenges

autonomous software component, having its own persistence and communicating with api

多个好处:Decomposing the platform's functionality into a set of autonomous software components provides a number of benefits:

好处1:deploy parts of system, integrating existing systems

好处2:replace components with customers'

好处3:being delievered and upgraded seperately

好处3:scaled out to serveral server instances independently

面临挑战:

挑战1:manually configuring load balancers and manually setting up new nodes. time-consuming and error-prone.

挑战2:chain of failures

挑战3:keepping the configuration consistent and up-to-date in all of instances of components

挑战4:monitoring, in terms of latency issues and hardware usage(CPU, memory, disk and the network)

挑战5 collecting log files and correlating related log events

  • What is a microservice-based architecture?

defining microservice: splitting up a monolithic application into smaller components, achieving two goals:

1. faster development, enabling continuous deployments

2.easier to scale, manually or automatically

an autonomous software component: independently upgradable and scalable

条件1:mircroservices don't share data in database

条件2:communicating with well defined interface

条件3:deployed as seperate runtime processes, such as docker

条件4:microservice instance is stateless

How big should a microservice be?

1.small enough  to fit to the head of a develper

2.not jeopardize performance(latency) or data consistency

  • Challenges with microservices

1.many small components, synchronise communication, a chain of problems

2.configuration up-to-date, many small components,  challenging

3.track a request involved many components, root cause analysis, log events locally

4.analyzing the usage of hardware resources

5.manual configuration, error prone

the 8 fallacies of distributed system

1.the network is reliable

2.latency is zero

3.bandwidth is infinite

4.the network is secure

5. topology doesnt change

6.there is an adminstrator

7.transport cost is zero

8.the network is homogenous

the rule of thumb:

detecting problems, restarting failed components, request to failed component should be resumed when fixed, all of these need to be fully automated.

  • Design patterns for handling challenges

the design patterns:

service discovery, edge server, reactive microservices, central configuration, centralized log analysis, distributed tracing, circuit breaker, control loop, centralized monitor and alarm.

spring boot, spring cloud, kubernetes

service discovery

problem: discover microservice

solution: a service discovery service

solution requirments:

1.automatically register or unregister microservices

2.logic endpoint,  request will be routed to one of the microservices

3.load banlance

4. detect instances that are not currently healthy.

two different strategy:

1.client side routing

2.server side routing

edge server:

problems:expose some of the microservices to the outside, and hide the remaining. protected against the requists from malicious clients.

solution:edge server that all incoming requists will go through.

reverse proxy, intergrated with discover service to provide dynamic load balancing capabilities.

solution requirments:

1.internal services should not be exposed to outside; only ruote requests to microservices that are configured to allow external requiests.

2.expose and protect external services from malicious requiests, use OAuth, OIDC, JWT TOKENs and api keys to ensure the clients are trustworthy.

reactive service

problem:synchronize communication using blocking I/O(a restful json api over http),the number of concurrent requests, longer response time, crashing server. overusing breaking I/O, error prone,  a chain of failures, Circuit Breaker,.

solution: use non-blocking I/O, no thread are allocated while waiting

solution requirements: an asynchronous programming model, resilient

central configuation

problem: how do I get a complete picture of configuration, how do I update the configuration

solution: a configuration server

solution requirments: store configuration information for a group of microservices, with different settings for different enviroments(dev, test, prod, qa)

centalized log analysis

problem: How I get an overview of what is going on in the system landscape?find out microservices getting into trouble and start writing error message, find related log messages, Identify which microservice instance is the root cause of the problem

solution: centralized logging,

collecting new logs, interpreting and storing log events in a structured and searchable way in a central database

providing APIs and graphic tools

distributed tracing:

problem: track requests and messages that flow between microservices

ideantify the root cause, find log message related to a specific order number

solution:correlation ID

solution requirments:assign correltion ID to a request, add the correlation ID when a micrservice makes a request.  add the correlation ID to all log events

circuit breaker

problem: synchronized intercommunication, a chain of failure

synchronous requests, blocking I/o

solution: a circuit breaker that prevents new and outgoing requests.

solution requirements: open the circuit and fail fast

probfor failure correction(half open circuit)

close the circuit if the probs detect the service is healed (self heal)

control loop

problem: difficult to manually detect and correct problems

solution:

a control loop constantly observers and , if required, takes action

solution requirements:

kubernetes

centralized monitoering and alarms

problem:

very hard to discover the root cause of problem

solution:

a monitor service

solution rquirements:

collect metrics from all the servers

detect new microservice instance

privide apis and graphic tools

  • Software enablers that can help us handle these challecornges

spring boot

spring cloud

Docker

Kubernates

Istio(a service mesh)

  • Other important considerations that aren't covered in this book

other important configuration

1.Importance of dev/ops: shorter delivery time,

2.conway's law:

3.decomposing a monolithic application into microservices:slow delivery, slow performance, inconsistant data

4.importance of api design: the same concept, the same description in terms of naming and data type; evolve in a controller manner

5.migration path from on-premise to the cloud

6.good design principles for microservices, the 12 factor api

 

Book Description Build a microservices architecture with Spring Boot, by evolving an application from a small monolith to an event-driven architecture composed of several services. This book follows an incremental approach to teach microservice structure, test-driven development, Eureka, Ribbon, Zuul, and end-to-end tests with Cucumber. Author Moises Macero follows a very pragmatic approach to explain the benefits of using this type of software architecture, instead of keeping you distracted with theoretical concepts. He covers some of the state-of-the-art techniques in computer programming, from a practical point of view. You'll focus on what's important, starting with the minimum viable product but keeping the flexibility to evolve it. What You'll Learn Build microservices with Spring Boot Use event-driven architecture and messaging with RabbitMQ Create RESTful services with Spring Master service discovery with Eureka and load balancing with Ribbon Route requests with Zuul as your API gateway Write end-to-end rest tests for an event-driven architecture using Cucumber Carry out continuous integration and deployment Who This Book Is For Those with at least some prior experience with Java programming. Some prior exposure to Spring Boot recommended but not required. Table of Contents Chapter 1: Introduction Chapter 2: The Basic Spring Boot Application Chapter 3: A Real Three-Tier Spring Boot Application Chapter 4: Starting with Microservices Chapter 5: The Microservices Journey Through Tools Chapter 6: Testing the Distributed System Appendix A: Upgrading to Spring Boot 2.0
### 使用Spring Boot实现微服务架构的最佳实践 #### 1. 构建基础环境和服务注册中心 为了创建可靠的微服务体系结构,首先需要设置一个服务发现机制。通常采用Eureka作为服务注册与发现组件。通过引入`spring-cloud-starter-netflix-eureka-server`依赖项来建立服务中心实例。 ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> ``` 接着编写简单的启动类并启用相应的功能: ```java package com.example.eurekaserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } } ``` 这一步骤确保了所有后续的服务能够相互识别并与之通信[^3]。 #### 2. 开发独立的业务逻辑模块 每一个单独运行的应用程序都代表了一个具体的功能单元——即所谓的“微服务”。这些服务应该围绕着特定领域模型构建,并保持高度内聚性和低耦合度。例如订单处理、库存管理和用户认证等都可以被划分为不同的微服务。 对于每个新创建的服务而言,除了必要的业务代码外还需要做两件事情:一是向Eureka服务器注册自己;二是声明对外提供哪些API接口供其他服务调用。下面给出一段典型的服务端点定义方式: ```java @RestController @RequestMapping("/api/v1/products") public class ProductController { private final ProductService productService; @Autowired public ProductController(ProductService productService){ this.productService = productService; } @GetMapping("/{id}") public ResponseEntity<ProductDTO> getProductById(@PathVariable Long id){ return ResponseEntity.ok(productService.findById(id)); } } ``` 同时记得在主应用程序中开启服务发现支持以便于自动完成上述操作: ```java @SpringBootApplication @EnableDiscoveryClient public class ProductServiceApplication { public static void main(String[] args) { SpringApplication.run(ProductServiceApplication.class, args); } } ``` 此过程有助于形成清晰的服务边界以及促进团队间的协作效率提升[^1]。 #### 3. 配置负载均衡器和网关层 随着系统的扩展可能会有多个相同类型的实例存在网络环境中,此时就需要借助Ribbon或Feign这样的工具来进行客户端侧的负载均衡。而Zuul/Zuul2则更适合充当整个集群前面的一道防护墙兼路由代理的角色,负责转发请求至目标地址的同时也承担起安全控制的任务。 以Zuul为例展示其基本配置方法如下所示: ```yaml zuul: routes: product-service: path: /products/** service-id: PRODUCT-SERVICE ribbon: eureka: enabled: true hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 5000 feign: hystrix: enabled: true ``` 以上设定不仅实现了动态调整流量分配的目的还增强了整体架构的安全性和稳定性[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值