壹、零基础
一、微服务架构零基础理论入门
SpringCloud=分布式微服务架构的一站式解决方案,是多种微服务架构落地技术的集合体,俗称微服务全家桶。
二、从2.2.x和H版开始说起
springboot版本选择:
git源码地址:https://github.com/spring-projects/spring-boot/releases/
SpringBoot2.0新特性:https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Release
springcloud版本选择:
git源码地址:https://github.com/spring-projects/spring-cloud
官网:https://spring.io/projects/spring-cloud
官网看cloud版本
springcloud和springboot之间依赖关系:https://spring.io/projects/spring-cloud#overview
三、关于Cloud各种组件的停更/升级/替换
服务注册中序:Eureka(挂)。zookeeper。Consul。Nacos(百万级推荐)。
服务调用1:Ribbon。LoadBalancer。
服务调用2:Feign(挂)。OpenFeign。
服务降级:Hystrix(挂)。resilience4j。sentienl(推荐)。
服务网关:Zuul(挂)。Zuul2(未出)。gateway(推荐)。
服务配置:Config(挂)。Nacos(推荐)。
服务总线:Bus(挂)。Nacos(推荐)。
参考资料:
1. Spring Cloud:https://cloud.spring.io/spring-cloud-static/Hoxton.SR1/reference/htmlsingle/
2. Spring Cloud中文文档:https://www.bookstack.cn/read/spring-cloud-docs/docs-index.md
3. Spring Boot:https://docs.spring.io/spring-boot/docs/2.2.2.RELEASE/reference/htmlsingle/
四、微服务架构编码构建
4.1 引入依赖
<!-- 统一管理jar包版本 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<lombok.version>1.16.18</lombok.version>
<mysql.version>5.1.47</mysql.version>
<druid.version>1.1.16</druid.version>
<mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version>
</properties>
<!-- 子模块继承之后,提供作用:锁定版本+子modlue不用写groupId和version -->
<dependencyManagement>
<dependencies>
<!--spring boot 2.2.2-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud Hoxton.SR1-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud alibaba 2.1.0.RELEASE-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.spring.boot.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<optional>true</optional>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.2.1.RELEASE</version>
<configuration>
<fork>true</fork>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
DependencyManagement和Dependencies的区别:
<DependencyManagement>是父类定义的坐标版本号,用在父工程,类似于规范将全工程的版本统一,只负责定义,而不负责引入实现。真正引入依赖的是子类<dependencies>定义的版本号。如果子类没指定版本号,默认是用父类的。如果子类指定了版本号,则版本号用子类指定的(如果不在子项目中声明依赖,不会从父项目中继承。只要在子项目中写了该依赖项,并且没有指定具体的版本,才会从父项目中继承该项,并且version和scope都读取自父pom)。
maven中跳过单元测试:
4.2 支付模块构建
1.建module:右键项目新建Module
2.改POM
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!--mysql-connector-java-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3. 写YML
在cloud-provider-payment8001的resources下创建application.yml文件,注意要变成绿色树叶:
server:
port: 8081
spring:
application:
name: cloud-payment-service
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db2019?useUnicode=true&characterEncoding=utf-8&usrSSL=false
username: root
password: 111111
mybatis:
mapper-locations: classpath:mapper/*.xml #在mapper包下创建.xml配置文件
type-aliases-package: com.atguigu.springcloud.entities #entities下创建实体类
4. 主启动
在src/main/java/com/atguigu/springcloud包下创建PaymentMain8001类,加上@SpringBootApplication作为主启动类:
@SpringBootApplication
public class PaymentMain8001 {
public static void main(String[] args){
SpringApplication.run(PaymentMain8001.class,args);
}
}
5. 业务类
5.1 建表SQL
CREATE TABLE `payment`(
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`serial` varchar(200) DEFAULT '',
PRIMARY KEY(`id`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
5.2 entities实体类
在java/com/atguigu/springcloud下创建entities包,在其下创建Payment类:
主实体Payment代码:
public class Payment implements Serializable {
private Long id;
private String serial;
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
public String getSerial() {return serial;}
public void setSerial(String serial) {this.serial = serial;}
public Payment(Long id, String serial) {this.id = id;this.serial = serial;}
public Payment() {}
}
Json封装体CommonResult
在entities包下创建CommonResult类:
public class CommonResult<T> {
private Integer code;
private String message;
private T data;
public CommonResult(Integer code,String message){this(code,message,null);}
public CommonResult(Integer code, String message, T data) {this.code = code;this.message = message;this.data = data;}
public CommonResult() {}
public Integer getCode() {return code;}
public void setCode(Integer code) {this.code = code;}
public String getMessage() {return message;}
public void setMessage(String message) {this.message = message;}
public T getData() {return data;}
public void setData(T data) {this.data = data;}
}
1. @Data
是一个Lombok注解,用于自动生成Java类的常见方法,如getter、setter、toString、equals和hashCode方法。
2. this(code, message, null)
表示调用当前类的另一个构造函数CommonResult(Integer code, String message, Object data)
,并传递参数code
、message
和null。
3. @AllArgsConstructor
是Lombok注解之一,用于自动生成一个包含所有参数的构造函数。
5.3 dao
创建dao包,在其下创建PaymentDao接口,记得写@Mapper注解:
@Mapper
public interface PaymentDao {
public int create(Payment payment);
public Payment getPaymentById(@Param("id") Long id);
}
mybatis的映射文件:
在resources下创建mapper包,创建PaymentMapper.xml映射文件:
1. parameterType是用来指定传入SQL语句的参数类型。
2. resultMap用来指定查询结果映射到哪个Java对象上。
3. column是数据库字段,property是java对象属性。
4.keyProperty
:用于指定自动生成的主键值要被设置到Java实体类的哪个属性上。
resultMap映射属性,用于防止命名不规范造成错误:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.springcloud.dao.PaymentDao">
<insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">
insert into payment(serial) values(#{serial});
</insert>
<resultMap id="BaseResultMap" type="com.atguigu.springcloud.entities.Payment">
<id column="id" property="id" jdbcType="BIGINT"/>
<id column="serial" property="serial" jdbcType="VARCHAR"/>
</resultMap>
<select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap">
select * from payment where id=#{id};
</select>
</mapper>
5.4 service
在springcloud下创建service包,创建PaymentService接口:
public interface PaymentService{
public int create(Payment payment);
public Payment getPatmentById(@Param("id") Long id);
}
1. @Param注解的作用是给方法参数起别名,@Param注解的作用是给方法参数起别名。@Param("id")表示给方法参数id起别名为"id"。这样在SQL映射文件中可以使用#{id}来引用这个参数。
创建PaymentServiceImpl实现类,记得写@Service注解
1. @Resource注解是用来标记一个需要依赖注入的对象。可以根据名称进行依赖注入,也可以根据类型进行依赖注入。
@Service
public class PaymentServiceImpl implements PaymentService {
@Resource
private PaymentDao paymentDao;
public int create(Payment payment) {
return paymentDao.create(payment);
}
public Payment getPatmentById(Long id) {
return paymentDao.getPaymentById(id);
}
}
5.5 controller
在springcloud下创建controller包,然后创建PaymentController类:
1. @GetMapping注解用于将HTTP的GET请求映射到相应的处理方法上。
2. @PathVariable注解用于将URL路径中的变量值绑定到方法参数上。
@RestController
public class PaymentController {
@Resource
private PaymentService paymentService;
@PostMapping(value="/payment/create")
public CommonResult create(Payment payment){
System.out.println(payment.getSerial());
int result = paymentService.create(payment);
if(result>0){
return new CommonResult(200,"插入数据库成功",result);
}else{
return new CommonResult(444,"插入数据库失败",null);
}
}
@GetMapping(value="/payment/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id)
{
Payment payment = paymentService.getPatmentById(id);
if(payment != null){
return new CommonResult(200,"查询成功",payment);
}else{
return new CommonResult(444,"没有对应记录,查询ID:"+id,null);
}
}
}
5.6 测试
启动启动类,在地址栏输入localhost:8001/payment/get/31
浏览器不适合发post请求,因此去postman发请求,id是自增的,只需要发送serial即可:
4.3 热部署
Devtools热部署,代码改动,自动重启。
第1步:在cloud-provider-payment8001添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
第2步:父工程cloud2020添加插件
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.2.1.RELEASE</version>
<configuration>
<fork>true</fork>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
第3步:开启自动编译权限
第4步:更新值,开启热注册
输入快捷键:ctrl + shift + alt + /
第5步:重启
(失败)测试:同样是PaymentMain8001启动,然后进入到cloud-provider-payment8001下的controller,更改CommonResult为CommonResult<Payment>,会实时刷新(失败)。
4.4 消费者订单模块
1. 建module
名字:Cloud-consumer-order80,src下有main和test,main下有java和resource
2. 改pom
web、acuator是图形化的监控展现,要先加mybatis的驱动运行,之后可以删除mybatis驱动,不然.yml会变不成绿叶:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
</dependencies>
3. 写YML
在resources下建application.yml,设置端口80
server:
port: 81
4. 主启动
在java下创建com.atguigu.springcloud.OrderMain80类
@SpringBootApplication
public class OrderMain81 {
public static void main(String[] args){
SpringApplication.run(OrderMain81.class,args);
}
}
5. 业务类
5.1 entities复制payment8001的
RestTemplate提供了多种便捷访问远程Http服务的方法,是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集。
5.2 创建springcloud下的config包,在包下创建ApplicationContextConfig类:
@Configuration
public class ApplicationContextConfig{
@Bean
public RestTemplate getRestTemp(){
return new RestTemplate();
}
}
5.3 在controller包下创建OrderController类:
@RestController
@Slf4j
public class OrderController{
public static final String PAYMENT_URL = "http://localhost:8081";
@Resource
private RestTemplate restTemplate;
@PostMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
}
但此时调用create方法会出现插入值为空的情况,记得要在cloud-provider-payment8001的controller下的PaymentController类中加入@RequestBody注解:
@RequestBody
注解用于将HTTP请求的请求体部分映射到方法的参数上。
新版的Dashboard叫作services
4.5 重构
新建一个cloud-api-commons模块,作为通用封装类:
在模块下引入依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.1.0</version>
</dependency>
<dependencies>
在模块的java目录下建com.atguigu.springcloud.entities包,直接将entities粘贴在下面:
点击右边的Maven,选择刷新出现cloud-api-commons,进入Lifecycle点击clean点击install即可。
删除掉原先的entities包
将下面依赖粘贴在删掉entities包的模块之下:
<dependency>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
贰、初级
五、Eureka服务注册与发现
7001、7002模拟的是Eureka服务器,81模拟消费者,8081和8082模拟生产者。
5.1 基础知识
5.2 服务端安装
1. 建module
ArtifactId:cloud-eureka-server7001,com.atguigu.springcloud
2. 改POM
<dependencies>
<!--eureka-server-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</deoendency>
<dependency>
<groupId>org.atguigu.springcloud</groupId>
<artifactId>cloud-api-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3. 写YML
在resources下创建application.yml
server:
port: 7001
eureka:
instance:
hostname: localhost #eureka服务端实例名称
client:
#false表示不向注册中心注册自己
register-with-eureka: false
#false表示自己端就是注册中心,我的职责就是维护服务实例,不需要检索服务
fetch-registry: false
service-url:
#设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
4. 主启动
创建EurekaMain7001作为启动类:
@SpringBootApplication
@EnableEurekaServer
public class EurekaMain7001{
public static void main(String[] args){
SpringApplication.run(EurekaMain7001.class,args);
}
}
如果成功输入localhost:7001后出现下面字样:
5.3 支付微服务8081入驻进eurekaServer
在8081的Pom中引入:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
在application.yml文件中增加如下代码:
eureka:
client:
#表示是否将自己注册进Eurekaserver默认为true
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡。
fetchRegistry: true
service-url:
defaultZone: http://localhost:7001/eureka
在启动类添加注解:@EnableEurekaClient
如果成功,Instances区域会出现CLOUD-PAYMENT-SERVICE这一新的Instances:
5.4 订单微服务81入驻进eurekaServer
在Pom中加入如下代码:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
在YML中加入如下代码:
eureka:
client:
register-with-eureka: true
fetchRegistry: true
service-url:
defaultZone: http://localhost:7001/eureka
在启动类中加入如下代码:@EnableEurekaClient
如果成功出现如下2个:
register-with-eureka为false表示不让入驻,为true表示让入驻。
5.5 集群原理说明
Eureka Server:服务注册,将服务信息注册进服务中心。服务发现,从注册中心上获取服务信息。实质,存key服务名 取 value调用地址。
先启动eureka注册中心。启动服务提供者payment支付服务。支付服务启动后会把自身信息(如服务地址以别名方式注册进eureka)。消费者order服务在需要调用接口时,使用服务别名去注册中心获取实际的RPC远程调用地址。消费者或者调用地址后,底层实际是利用HttpClient技术实现远程调用。消费者获取服务地址后会缓存在本地jvm内存中,默认每隔30秒更新一次服务调用地址。
Eureka具有高可用特点,可搭建Eureka注册中心集群,实现负载均衡+容错故障。避免单点故障。互相注册,相互守望。
5.6 集群环境构建
建Module:cloud-eureka-server7002
Pom:直接复制7001
YML:建application.yml
主启动类:EurekaMain7002,用7001的注解
修改配置:C:\Windows\System32\drivers\etc路径下的hosts文件。
修改7001的.yml,修改hostname和defaultZone:
server:
port: 7001
eureka:
instance:
hostname: eureka7001.com #eureka服务端实例名称
client:
#false表示不向注册中心注册自己
register-with-eureka: false
#false表示自己端就是注册中心,我的职责就是维护服务实例,不需要检索服务
fetch-registry: false
service-url:
#设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址
defaultZone: http://eureka7002.com:7002/eureka/
修改7002的.yml文件:
server:
port: 7002
eureka:
instance:
hostname: eureka7002.com #eureka服务端实例名称
client:
#false表示不向注册中心注册自己
register-with-eureka: false
#false表示自己端就是注册中心,我的职责就是维护服务实例,不需要检索服务
fetch-registry: false
service-url:
#设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址
defaultZone: http://eureka7001.com:7001/eureka/
输入eureka7002.com:7002==127.0.0.1:7002和eureka7001.com:7001==127.0.0.1能见到eureka首页:
输入
locahost:7002能指向7001,locahost:7001能指向7002算是成功:
5.7 订单支付两微服务注册进Eureka集群
YML:在8081的eureka下添加:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
YML:在81的eureka下添加:
eureka:
client:
register-with-eureka: true
fetchRegistry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
启动:
先要启动EurekaServer,7001/7002服务
再启动服务提供者provider,8081
再启动消费者,81
输入http://localhost:81/consumer/payment/get/31,如果查询成功即可
测试:
eureka7001.com:7001可以看到81和8081注册进入
eureka7002.com:7002同样也可以看到
5.8 支付微服务集群配置
建Module:创建cloud-provider-payment8082
改Pom:把8081粘贴入8082
写YML:把8081的粘贴入8082,改一个端口号
主启动:建PaymentMain8082把8081的启动类复制过来,把resource下的mapper包粘贴到8082,把com包直接粘贴到8082。
改controller:修改8001和8002加入如下内容:
@Value("${server.port}")
private String serverPort;
return new CommonResult(200,"插入数据库成功,serverPort"+serverPort,result);
return new CommonResult(200,"查询成功,serverPort"+serverPort,payment);
启动顺序:7001、7002、8081、8082、81
测试:eureka7001.com:7001,eureka7002.com:7002,localhost:81/consumer/payment/get/31
发现bug:订单服务访问地址是写死的。
此时会报错,因为IDEA不知道是这个地址下的哪台服务器提供服务。
使用@LoadBalanced注解赋予RestTemplate负载均衡的能力,注解写在config包的ApplicationContextConfig下:
此时访问localhost:81/consumer/payment/get/31,端口号会在8081和8082之间来回切换:
5.9 actuator微服务信息完善
加上instance: instance-id和prefer-ip-address: true(访问路径显示ip地址)
5.10 服务发现Discovery
在8081的controller的PaymentController类上修改:
@Slf4j
@RestController
public class PaymentController {
@Resource
private DiscoveryClient discoveryClient;
@GetMapping(value="/payment/discovery")
public Object discovery()
{
List<String> services = discoveryClient.getServices();
for(String element : services){
log.info("*****element: "+element);
}
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
for(ServiceInstance instance : instances){
log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
}
return instances;
}
}
5. 11 Eureka自我保护理论知识
概括:某时刻某一个微服务不可用了,Eureka不会立刻清理,依旧会对该微服务的信息进行保存。
为了防止EurekaClient可以正常运行,但是与EurekaServer网络不通情况下,EurekaServer不会立刻将EurekaClient服务器剔除。
5.12 禁止自我保护
在7001的yml文件中的eureka下,加下列代码:
server:
#关闭自我保护机制,保证不可用服务被及时踢除
enable-self-preservation: false
eviction-interval-timer-in-ms: 2000
测试:先看8081是否存在,关闭8081,看卡是否立刻删除。
Eureka停更说明
六、Zookeeper服务注册与发现
6.1 Zookeeper的安装
下载zookeeper-3.4.9,下面是安装地址
https://archive.apache.org/dist/zookeeper/
在Linux虚拟机中,创建/opt/module目录,把zookeeper的gz压缩包放到该目录下。
然后解压该压缩包到该目录:
tar -zxvf zookeeper-3.4.10.tar.gz -C /opt/module/
然后修改配置:
将/opt/module/zookeeper-3.4.10/conf这个路径下的zoo.sample.cfg修改为zoo.cfg:
mv zoo_sample.cfg zoo.cfg
在/opt/module/zookeeper-3.4.10目录创建zkData文件夹:
mkdir zkData
打开zoo.cfg文件,修改dataDir路径:
vim zoo.cfg
修改如下内容:
dataDir=/opt/module/zookeeper-3.4.10/zkData
启动Zookeeper服务
输入:sudo /opt/module/zookeeper-3.4.9/bin/zkServer.sh start
进入Zookeeper
输入:sudo /opt/module/zookeeper-3.4.9/bin/zkCli.sh
退出Zookeeper
输入:quit
关闭Zookeeper服务:
sudo /opt/module/zookeeper-3.4.9/bin/zkServer.sh stop
6.2 项目环境配置
在/opt/module/zookeeper-3.4.9/bin目录下输入:
sudo systemctl stop firewalld 关闭防火墙。
sudo systemctl status firewalld检查防火墙是否关闭。
确保虚拟机能和windows ping通
建module:cloud-provider-payment8004
pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
YML:
server:
port: 8004
#服务别名 — — — — 注册zookeeper到注册中心名称
spring:
application:
name: cloud-provider-payment
cloud:
zookeeper:
connect-string: 192.168.182.157:2181
启动类:
com.atguigu.springcloud.PaymentMain8004
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain8004 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8004.class,args);
}
}
服务类:
springcloud下建controller包,PaymentController
@RestController
@Slf4j
public class PaymentController {
@Value("${server.port}")
private String serverPort;
@RequestMapping(value="/payment/zk")
public String paymentzk(){
return "springcloud with zookeeper: "+serverPort+"\t"+ UUID.randomUUID().toString();
}
}
然后启动Zookeeper服务,进入zookeeper
输入:sudo /opt/module/zookeeper-3.4.9/bin/zkServer.sh start
输入:sudo /opt/module/zookeeper-3.4.9/bin/zkCli.sh
输入:get /zookeeper
版本冲突问题:
<dependency>
<!--添加zookeeper3.4.9版本-->
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.9</version>
<!--先排除自带的zookeeper3.5.3-->
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
然后点击启动。
测试localhost:8004/payment/zk,如果每次刷新后面一串数字会变则成功:
把json串赋值到tool.lu/json看得到信息则成功:
6.3 临时还是持久节点
用的是临时的,关闭8004一段时间,zookeeper会踢掉。重新启动,流水号会改变。
6.4 订单服务注册进zookeeper
module:cloud-consumerzk-order81。
POM:复制8004,见上节。
YML:
server:
port: 81
#服务别名 — — — — 注册zookeeper到注册中心名称
spring:
application:
name: cloud-consumer-order
cloud:
#注册到zookeeper地址
zookeeper:
connect-string= 192.168.182.157:2181
启动类:
@SpringBootApplication
@EnableDiscoveryClient
public class OrderZKMain81 {
public static void main(String[] args) {
SpringApplication.run(OrderZKMain81.class,args);
}
}
config:
@Configuration
public class ApplicationContextConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
controller:
@RestController
@Slf4j
public class OrderZKController {
public static final String INVOKE_URL="http://cloud-provider-payment";
@Resource
private RestTemplate restTemplate;
@GetMapping(value="/consumer/payment/zk")
public String paymentInfo(){
String result = restTemplate.getForObject(INVOKE_URL+"/payment/zk",String.class);
return result;
}
}
测试:
七、Consul服务注册与发现
7.1 Consul简介
7.2 安装并运行Consul
下载地址:
https://developer.hashicorp.com/consul/downloads
点击地址栏,输入cmd,输入consul --version,再输入consul agent -dev
输入http://localhost:8500会进入界面,看到勾勾:
7.3 服务提供者注册进Consul
module:cloud-providerconsul-payment8006
pom:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
yml:
server:
port: 8006
spring:
application:
name: consul-provider-payment
#consul注册中心地址
cloud:
consul:
host: localhost
port: 8500
discovery:
service-name: ${spring.application.name}
启动类:
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain8006 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8006.class,args);
}
}
业务类:复制8004,稍加修改
@RestController
@Slf4j
public class PaymentController {
@Value("${server.port}")
private String serverPort;
@RequestMapping(value="/payment/consul")
public String paymentzk(){
return "springcloud with consul: "+serverPort+"\t"+ UUID.randomUUID().toString();
}
}
测试类:启动
7.4 服务消费者注册进Consul
module: cloud-consumerconsul-order81
pom:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
yml:
server:
port: 81
spring:
application:
name: cloud-consumer-order
#consul注册中心地址
cloud:
consul:
host: localhost
port: 8500
discovery:
service-name: ${spring.application.name}
主启动类:
@SpringBootApplication
@EnableDiscoveryClient //该注解用于向使用consul或者zookeeper作为注册中心时注册服务
public class OrderConsulMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderConsulMain80.class,args);
}
}
配置Bean:
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
Controller:
@RestController
@Slf4j
public class OrderConsulController {
public static final String INVOKE_URL = "http://consul-provider-payment";
@Resource
private RestTemplate restTemplate;
@GetMapping(value = "/consumer/payment/consul")
public String paymentInfo(){
String result = restTemplate.getForObject(INVOKE_URL+"/payment/consul",String.class);
return result;
}
}
验证测试:启动
访问测试地址:
7.5 三个注册中心异同点
CAP:
AP是Eureka,是保证一致性。
不同网络分区数据同步失败,为了保证可用性,允许可以返回旧值,所以是违背了一致性要求。
CP是Zookeeper和Consul,是数据要一致,不一致就挂报错。
八、Ribbon负载均衡服务调用
8.1 Ribbon入门介绍
先恢复环境EurekaMain7001,EurekaMain7002,PaymentMain8081,PaymentMain8083,OrderMain81。
输入eureka7001.com:7001
基本介绍:
能做什么:
集中式:
进程内:
8.2 Ribbon的负载均衡和Rest调用
此时刷新网页发现已经可以实现轮询,却并未引入Ribbon,实际的原因是Eureka中已经自带了Ribbon。
在cloud-consumer-order81的OrderController中加入如下代码:
@GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPayment2(@PathVariable("id") Long id)
{
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
if(entity.getStatusCode().is2xxSuccessful()){
return entity.getBody();
}else{
return new CommonResult<>(444,"操作失败");
}
}
输入:localhost:81/consumer/payment/getForEntity/31
8.3 Ribbon默认自带的负载规则
8.4 Ribbon负载规则替换
ribbon替换规则要求不能把配置放在Main包上级一层的包以下,就是要在包外面自己创建一个。
在atguigu下面创建一个包叫作myrule。
在myrule下面创建MySelfRule类。
@Configuration
public class MySelfRule {
@Bean
public IRule myRule(){
return new RandomRule();
}
}
在OrderMain81上添加@RibbonClient注解:
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name="CLOUD-PAYMENT-SERVICE",configuration= MySelfRule.class)
public class OrderMain81 {
public static void main(String[] args){
SpringApplication.run(OrderMain81.class,args);
}
}
输入:localhost:81/consumer/payment/getForEntity/31,此时的访问是随机的
8.5 Ribbon默认负载轮询算法原理
8.6 RoundRobinRule源码分析
快捷键:alt+ctrl+b查看源码
8.7 Ribbon之手写轮询算法
1.注释掉cloud-consumer-order81配置类里的@LoadBalance
2.在springcloud下新建lb包,新建接口LoadBalancer
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
3.在lb包下实现类:MyLB
@Component
public class MyLB implements LoadBalancer{
private AtomicInteger atomicInteger = new AtomicInteger(0);
public final int getAndIncrement(){
int current;
int next;
do{
current = this.atomicInteger.get();
next = current >= 2147483647 ? 0:current+1;
}while(!this.atomicInteger.compareAndSet(current,next));
System.out.println("*****第几次访问,次数next:"+next);
return next;
}
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances){
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}
在controlle包下的OrderControlle写入如下代码:
@GetMapping(value="/consumer/payment/lb")
public String getPaymentLB(){
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
if(instances == null || instances.size() <= 0){
return null;
}
ServiceInstance serviceInstance = loadBalancer.instances(instances);
URI uri = serviceInstance.getUri();
System.out.println(uri);
System.out.println(uri+"/payment/lb");
return restTemplate.getForObject(uri+"/payment/lb",String.class);
}
@Resource
private LoadBalancer loadBalancer;
@Resource
private DiscoveryClient discoveryClient;
在8081和8083的PaymentController中写入如下代码:
@GetMapping(value="/payment/lb")
public String getPaymentLB(){
return serverPort;
}
输入地址:localhost:81/consumer/payment/lb,效果是8081和8083交替出现
九、OpenFeign服务接口调用
9.1 OpenFeig是什么
9.2 OpenFeign服务调用
接口+注解:微服务调用接口(提供方和调用方相吻合的接口)+@FeignClient
module:cloud-consumer-feign-order81
pom:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.atguigu.springcloud</groupId>
<artifactId>cloud-api-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
</dependencies>
yml:
server:
port: 81
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
主启动:
com.atguigu.springcloud.OrderFeignMain81添加@EnableFeignClients
@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain81 {
public static void main(String[] args) {
SpringApplication.run(OrderFeignMain81.class,args);
}
}
业务类:
在springcloud下添加service包,然后添加PaymentFeignService接口。
@Configuration
@FeignClient(value="CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping(value="/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}
controller下创建OrerFeignController
@RestController
@Slf4j
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping(value="/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
return paymentFeignService.getPaymentById(id);
}
}
测试:localhost:81/consumer/payment/get/31,出现8081和8083交替结果。
总结:Feign是一个声明式的Web服务客户端,它使得编写HTTP客户端变得更简单。我们只需要创建一个接口并在接口上添加注解,Feign就会自动提供实现,无需手动创建URL、发送HTTP请求、处理HTTP响应等。
该客户端会将请求发送到名为CLOUD-PAYMENT-SERVICE的服务。
9.3 OpenFeign超时控制
在8081的controller下的PaymentController添加如下代码:
@GetMapping(value="/payment/feign/timeout")
public String paymentFeignTimeout(){
try{
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return serverPort;
}
在81的service包下的PaymentFeignService接口下添加如下代码:
@GetMapping(value="/payment/feign/timeout")
public String paymentFeignTimeout();
在81的controller包下
@GetMapping(value="/consumer/payment/feign/timeout")
public String paymentFeignTimeout(){
//客户端默认等1秒
return paymentFeignService.paymentFeignTimeout();
}
测试:
启动7001,8001
localhost:8081/payment/feign/timeout,正常访问耗时秒
localhost:81/consumer/payment/feign/timeout时间超时
解决:
server:
port: 81
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
#设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
#指的是建立连接所用的时间,适用于网络状况正常的情况下,两段连接所用的时间
ReadTimeout: 5000
#指的是建立连接后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000
再测试成功。
9.4 OpenFeign日志增强
在cloud-consumer-feign-order80下的springcloud下创建config,配置日志bean:
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerlevel()
{
return Logger.Level.FULL;
}
}
在YML文件中添加如下代码:
logging:
level:
com.atguigu.springcloud.service.PaymentFeignService: debug
测试:启动Openfeign81。localhost/consumer/payment/get/31。
在控制台看调用结果:文章来源:https://www.toymoban.com/news/detail-718891.html
文章来源地址https://www.toymoban.com/news/detail-718891.html
到了这里,关于SpringCloud学习笔记(上):服务注册与发现:Eureka、Zookeeper、Consul+负载均衡服务调用:Ribbon的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!