软件编程
位置:首页>> 软件编程>> java编程>> SpringCloud Eureka的使用教程

SpringCloud Eureka的使用教程

作者:WillLiaowh  发布时间:2022-03-23 22:30:59 

标签:springcloud,eureka

什么是Eureka

Eureka是Netfilx开源的一个用来实现微服务的注册与发现的组件。它包含Server和Client两部分。

为什么要有Eureka

例如目前有两个服务分别为服务A,服务B,我们可以在服务A调用服务B的接口地址完成调用,但是当服务间的调用关系复杂起来的时候,比如服务A还需要调用服务CDE,那么服务A需要维护它调用的所有服务的地址,一旦地址的变更都需要手动去修改。

当使用了Eureka这样的服务治理框架后,服务ABCDE可以一起注册到EurekaServer服务上,直接通过服务名来调用其他服务。

Eureka的使用

通过Eureka,实现消费者服务80通过服务名调用服务提供者8001的接口。

cloud-eureka-server7001关键代码

引入server依赖:


<!--eureka-server-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

server端配置:


eureka:
instance:
hostname: localhost
client:
register-with-eureka: false #false表示不向注册中心注册自己。
fetch-registry: false #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
service-url:
#集群指向其它eureka
defaultZone: http://eureka7002.com:7002/eureka/
#单机就是7001自己
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

启动类注解:


@SpringBootApplication
@EnableEurekaServer
public class EurekaMain7001
{
public static void main(String[] args) {
  SpringApplication.run(EurekaMain7001.class, args);
}
}

cloud-provider-payment8001关键代码

引入client依赖:


<!--eureka-client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

client端配置:


eureka:
client:
#表示是否将自己注册进EurekaServer默认为true。
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetchRegistry: true
service-url:
defaultZone: http://localhost:7001/eureka

启动类注解:


@SpringBootApplication
@EnableEurekaClient
public class PaymentMain8001 {
public static void main(String[] args) {
 SpringApplication.run(PaymentMain8001.class, args);
}
}

cloud-consumer-order80

关键代码同服务提供者

通过服务名调用其他服务的接口(RestTemple记得要加@LoadBalanced,否则找不到服务名):


public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id)
{
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}

SpringCloud Eureka的使用教程

SpringCloud Eureka的使用教程

如果使用Eureka集群

EurekaServer配置


#集群指向其它eureka
defaultZone: http://eureka7002.com:7002/eureka/

服务Cient配置


# 集群
#defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka #

总结

来源:https://segmentfault.com/a/1190000038999454

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com