服务注册中心Eureka集群
介绍
Eureka是Sping Cloud Netflix的核心组件,在SpringCloud构架中的作用是实现服务的注册和发现, 遵循着CAP理论中的A(可用性)P(分区容错性), 一个Eureka中分为eureka server和eureka client。其中eureka server是作为服务的注册与发现中心。eureka client既可以作为服务的生产者,又可以作为服务的消费者。具体结构如下图:
上图显示的是Eureka集群,因为是分布式架构设计,不能用单机版,如果一旦是单机版,Eureka服务器宕机或者出现故障,网站就彻底瘫痪了。
Eureka现在已经处于停更,但是它的设计思想仍然保存,只是有不同的实现!
建议Springboot版本使用2.2.2、spring cloud Hoxton.SR1
Eureka Server实现
本次演示为Eureka集群版本,两个Eureka服务,需要两个模块
在本地运行时候因为要多个需要修改hosts文件实现本机映射关系
目录 :C:\Windows\System32\drivers\etc
127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com
127.0.0.1 eureka7003.com
spring cloud是基于spring boot进行的开发,因此我们需要创建一个spring boot项目或者是maven,同时在里面添加eureka server包。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
配置application.xml,一般Eureka都是在7000的端口,多个Eureka时候,依次排列,
集群配置要多个模块,配置eureka的defaultZone参数,两个以上可以用‘,’来注册
server:
port: 7001
eureka:
instance:
hostname: eureka7001.com # eureka 服务端的实例名称
client:
register-with-eureka: false # false 表示不向注册中心注册自己
fetch-registry: false # false 表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
service-url:
defaultZone: http://eureka7002.com:7002/eureka/ #设置与Eureka server 交互的地址查询服务和注册服务都需要依赖这个地址。
server:
enable-self-preservation: false #关闭自我保护机制,保证不可用服务被及时踢出
eviction-interval-timer-in-ms: 2000 #保护的时间
设置主启动类 @EnableEurekaServer 注解开启Eureka服务端
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* author : 三生石
* Blog : https://jiazhibo.top/
* date : 2022/4/8 15:08
* description:
*/
@EnableEurekaServer //在主启动类中开启Eureka
@SpringBootApplication
public class EurekaMain7001 {
public static void main(String[] args) {
SpringApplication.run(EurekaMain7001.class,args);
}
}
启动模块后访问 http://eureka7002.com:7001/ 如下图:
出现此图Eureka服务端配置完成
Eureka Client实现
服务提供者
本次使用的是两个服务提供者
首先第一步也是导包
Zipkin 是基于 Dapper 论文实现,由 Twitter 开源的分布式追踪系统,通过收集分布式服务执行时间的信息来达到追踪服务调用链路、以及分析服务执行延迟等目的。
<!--包含了sleuth+zipkin-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<!--eureka-client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置yml文件(本配置类没有加入MySQL的数据配置和mybatis的配置,这个可自行配置)
server:
port: 8001
spring:
application:
name: cloud-payment-service
eureka:
client:
# 是否將自己注冊到EurekaServce 默認為true。
register-with-eureka: true
# 是否从EurekaServer抓取即有的注册信息,默认为true 单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetch-registry: true
service-url:
# defaultZone: http://localhost:7001/eureka 单机版的
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka #集群版
instance:
instance-id: payment8001 #主机名称
prefer-ip-address: true #访问路径可以显示IP地址
lease-renewal-interval-in-seconds: 1 #Eureka 客户端向服务端发送心跳的时间间隔,单位为秒,(默认是30秒)
lease-expiration-duration-in-seconds: 2 #Eureka 服务端在最后一次心跳等待时间上线,单位为秒, (默认是90秒),超市将剔除服务
编辑主启动类,这里不再演示,需要注意的是在主启动类中添加@EnableEurekaClient 注解开启Eureka客户端,编辑Controller层,用来提供服务
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* author : 三生石
* Blog : https://jiazhibo.top/
* date : 2022/4/8 12:10
* description:
*/
@RestController
@Slf4j
public class PaymentController {
@Resource
private PaymentService paymentService;
@Value("${server.port}")
private String serverPort;
// 可以通过服务发现来获得该服务的信息
@Resource
private DiscoveryClient discoveryClient;
//只传给前端CommonResult,不需要前端了解其他的组件
@PostMapping(value = "/payment/create")
public CommonResult create(@RequestBody Payment payment){
int result = paymentService.create(payment);
log.info("*****插入结果:"+result);
if(result > 0){
return new CommonResult(200,"插入数据成功,serverPort:"+serverPort,result);
}else{
return new CommonResult(444,"插入数据失败,serverPort:"+serverPort,null);
}
}
@GetMapping(value = "/payment/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id){
Payment payment = paymentService.getPaymentById(id);
log.info("*****插入结果:"+payment);
if(payment != null){
return new CommonResult(200,"查询成功。serverPort:"+serverPort,payment);
}else{
return new CommonResult(444,"没有对应记录,查询ID:"+id+"ServerPort"+serverPort,null);
}
}
/**
* 获取服务的所有信息
* @return
*/
@GetMapping(value = "/payment/discovery")
public Object discovery(){
//获取的是所有的服务
List<String> services = discoveryClient.getServices();
for (String service : services) {
log.info(">>>>element:"+service);
}
// 获得的是服务下的所有实例
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()+"\t"
);
}
return this.discoveryClient;
}
}
服务消费者
首先pom.xml、主启动类和服务消费者一至,
application.yml文件
server:
port: 80
spring:
application:
name: cloud-order-service
eureka:
client:
# 是否將自己注冊到EurekaServce 默認為true。
register-with-eureka: true
# 是否从EurekaServer抓取即有的注册信息,默认为true 单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetch-registry: true
service-url:
# defaultZone: http://localhost:7001/eureka 单机版的
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka #集群版
需要注意消费者的controller
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
/**
* author : 三生石
* Blog : https://jiazhibo.top/
* date : 2022/4/8 13:38
* description:
*/
@RestController
@Slf4j
public class OrderController {
// 引用RestTemplate调用消费者服务端的AIP
@Resource
private RestTemplate restTemplate;
// 这里的URL是消费方的,第一个只是准确的url,不能显示负载均衡,第二个使用的是服务名称调用,可以实现调用不同的服务实例
// public static final String PAYMENT_URL = "http://localhost:8001";
public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
@GetMapping("/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")String id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
}
最后编辑配置类,因为引用了RestTemplate和开启了负载均衡
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* author : 三生石
* Blog : https://jiazhibo.top/
* date : 2022/4/8 13:47
* description:
*/
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced //开启负载均衡, 默认轮询
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
大功告成,此时两个服务提供者和一个服务消费者,用户在调用服务提供者时候就可以进入不同的服务实例。
- 公共的实体类
- 服务消费者客户端80端口
- Eureka服务注册服务端
- Eureka服务注册服务端
- 服务消费者8001
- 服务消费者8002
服务消费者通过Eureka集群找到对应的服务消费者,通过LoadBalanced 轮询的方式找到对应的实例,从而实现负载均衡
评论区