# springcloud-learn
**Repository Path**: carp-notes/springcloud-learn
## Basic Information
- **Project Name**: springcloud-learn
- **Description**: springcloud学习笔记
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 1
- **Created**: 2021-12-20
- **Last Updated**: 2026-01-08
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# 一、微服务架构
微服务架构是一种架构模式,它提倡将单一应用划分成一组小的服务,服务之间互相协调、互相配合,为用户提供最终价值。每个服务运行在其独立的进程中,服务与服务间采用轻量级的通信机制互相协作(通常是基于HTTP协议的RestFul API)。每个服务都围绕着具体业务进行构建,并且能够被独立的部署到生产环境、类生产环境等。另外,应当尽量避免统一的、集中式的服务管理机制,对具体的一个服务而言,应根据上下文,选择合适的语言、工具对其进行构建。
SpringCloud是分布式微服务一站式解决方案,是多种微服务架构落地技术的集合体,俗称微服务全家桶

# 二、版本选择
##### SpringCloud: 2020.0.3
1)查看SpringCloud最新稳定版

2)查看SpringCloud版本依赖,https://start.spring.io/actuator/info
```json
{
...
"bom-ranges": {
...
"spring-cloud": {
"Hoxton.SR12": "Spring Boot >=2.2.0.RELEASE and <2.4.0.M1",
"2020.0.4": "Spring Boot >=2.4.0.M1 and <2.5.6-SNAPSHOT",
"2020.0.5-SNAPSHOT": "Spring Boot >=2.5.6-SNAPSHOT and <2.6.0-M1",
"2021.0.0-M1": "Spring Boot >=2.6.0-M1 and <2.6.0-M3",
"2021.0.0-M2": "Spring Boot >=2.6.0-M3 and <2.6.0-SNAPSHOT",
"2021.0.0-SNAPSHOT": "Spring Boot >=2.6.0-SNAPSHOT"
},
...
},
...
}
```
3)查看SpringCloud推荐Springboot版本

# 三、组件使用

# 四、注册中心
## 4.1、Eureka
### 1、Eureka基础知识
#### 服务治理
Spring Cloud 封装了 Netflix 公司开发的 Eureka 模块来实现服务治理。
在传统的rpc远程调用框架中,管理每个服务与服务之间依赖关系比较复杂,管理比较复杂,所以需要使用服务治理,**管理服务于服务之间依赖关系,可以实现服务调用、负载均衡、容错等,实现服务发现与注册**。
#### 服务注册和发现
Eureka采用了CS的设计架构,Eureka Server作为服务注册功能的服务器,它是服务注册中心。而系统的其他微服务,使用Eureka的客户端连接到Eureka Server并维持心跳连接。这样的维护人员就可以通过Eureka Server来监控系统中各个微服务是否正常运行。
#### Eureka组件:Eureka Server、Eureka Client
Eureka Server提供服务注册服务;各个微服务节点通过配置启动后,会在EurekaServer中进行注册,这样EurekaServer中的服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观看到。
EurekaClient通过注册中心进行访问是一个Java客户端,用于简化Eureka Server的交互,客户端同时也具备一个内置的、使用轮询(round-robin)负载算法的负载均衡器。在应用启动后,将会向Eureka Server发送心跳(默认周期为30秒)。如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,EurekaServer将会从服务注册表中把这个服务节点移除(默认90秒)
### 2、Eureka单机
#### 1)、EurekaServer
###### (a)pom.xml
导入spring-cloud-starter-netflix-eureka-server包
```xml
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
```
###### (b)application.yml
完善eureka服务
```yaml
server:
port: 8001
servlet:
context-path: /provider-payment # 服务上下文路径
spring:
application:
name: provider-payment # 服务名
eureka:
instance:
# eureka服务端的实例名称
hostname: localhost
client:
# 不向注册中心注册自己
register-with-eureka: false
# false表示自己就是注册中心,职责是维护服务实例,并不需要检索服务
fetch-registry: false
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
```
###### (c)Application.java

#### 2)、EurekaClient
(a)pom.xml
```xml
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
```
(b)application.yml
```yaml
server:
port: 8001
servlet:
context-path: /provider-payment
spring:
application:
name: provider-payment
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/cloud-01-payment?useUnicode=true&characterEncoding=utf-8&useSSL=false&useOldAliasMetadataBehavior=true
username: root
password: root
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.liyu.commons.entity
eureka:
client:
# 将自己注册进服务注册中心
register-with-eureka: true
# 是否从注册中心抓取已有的注册信息,默认为true,集群必须设置为true,才能配合ribbon使用负载均衡
fetch-registry: true
service-url:
defaultZone: http://localhost:8000/eureka
```
(c)Application.java

#### 3)、效果
访问EurekaServer服务注册中心

### 3、Eureka集群
#### 1)、hosts

#### 2)、EurekaServer

#### 3)、EurekaServer2

#### 4)、EurekaClient

5)、效果

### 4、Eureka消费客户端
#### 1)使用RestTemplate
###### (a)pom.xml
```xml
com.liyu
03-api-commons
${project.parent.version}
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-actuator
org.projectlombok
lombok
org.springframework.boot
spring-boot-starter-test
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.boot
spring-boot-maven-plugin
2.5.6
true
```
###### (b)application.yml
```yaml
server:
port: 8101
servlet:
context-path: /provider-order
spring:
application:
name: provider-order
eureka:
client:
# 将自己注册进服务注册中心
register-with-eureka: true
# 是否从注册中心抓取已有的注册信息,默认为true,集群必须设置为true,才能配合ribbon使用负载均衡
fetch-registry: true
service-url:
# defaultZone: http://localhost:8000/eureka
defaultZone: http://eureka.server1.com:8000/eureka/,http://eureka.server2.com:9000/eureka/
```
###### (c)Application.java
```java
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@EnableEurekaClient
public class ConsumerOrderApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerOrderApplication.class,args);
}
}
```
###### (d)ContextConfig.java
```java
@Configuration
public class ContextConfig {
@Bean
@LoadBalanced // 负载均衡使用
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
```
###### (d)OrderController.java
```java
@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {
public static final String PAYMENT_URL = "http://PROVIDER-PAYMENT";
@Resource
private RestTemplate restTemplate;
@Resource
private DiscoveryClient discoveryClient;
@GetMapping("{id}")
public Result get(@PathVariable("id") Long id) {
return restTemplate.getForObject(PAYMENT_URL + "/provider-payment/payment/" +id, Result.class);
}
@GetMapping("/discovery")
public Result> getDiscovery() {
List services = discoveryClient.getServices();
services.stream().forEach(service -> {
log.info("--------------service-name:" + service+"------------------------------");
List instances = discoveryClient.getInstances(service);
instances.stream().forEach( instance -> {
log.info("instance-name:" + instance.getServiceId());
});
log.info("-------------------------------------------------------------------------");
});
return new Result<>(200, services, null);
}
}
```
## 4.2、Zookeeper
### 1、集成Zookeeper
#### 1)、Provider生产者
###### (a)pom.xml
需要引用spring-cloud-starter-zookeeper-discovery包
```xml
......
org.springframework.cloud
spring-cloud-starter-zookeeper-discovery
......
```
###### (b)application.yml
配置服务名,和Zookeeper服务ip、端口,集群使用“,”分隔
```yaml
server:
port: 8101
spring:
application:
name: provider-payment # 服务名
cloud:
zookeeper:
connect-string: 123.56.163.139:2181 #zookeeper注册中心
```
###### (c)Application.java
给启动类添加**@EnableDiscoveryClient**注解
```java
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
// @EnableDiscoveryClient注解用于向Consul或Zookeeper服务中心注册服务
@EnableDiscoveryClient
public class PaymentApplicaion {
public static void main(String[] args) {
SpringApplication.run(PaymentApplicaion.class, args);
}
}
```
###### (d)实现生产者服务
```java
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {
@Resource
private ServerProperties serverProperties;
@GetMapping("{id}")
public Result