服务注册与发现-Eureka概述与简单使用

本文内容基于SpringCloud概述和学习项目预搭建中搭建的工程

作用

Spring Cloud封装了Netflix公司开发的Eureka模块来实现服务治理

Eureka是个基于REST的服务,SpringCloud将它集成在其子项目中,以实现SpringCloud的服务发现功能,SpringCloud重要组成组件。

在传统的rpc远程调用框架中,管理每个服务与服务之间依赖关系比较复杂,管理比较复杂,所以需要使用服务治理,管理服务与服务之间的依赖关系,可以实现服务调用、负载均衡、容错等,实现服务发现与注册。

组件

Eureka包含两个组件: Eureka ServerEureka Client

服务注册与发现-Eureka概述与简单使用

(图片来源:https://blog.csdn.net/qwe86314/article/details/94552801)

Eureka Server提供服务注册服务:

各个微服务节点通过配置启动后,会在Eureka Server中进行注册, 这样Eureka Server中的服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观看到。

EurekaClient通过注册中心进行访问:

是一个Java客户端,用于简化Eureka Server的交互,客户端同时也具备一个内置的、使用轮询(round-robin)负载算法的负载均衡器。在应用启动后,将会向Eureka Server发送心跳(默认周期为30秒)。如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,Eureka Server将会从服务注册表中把这个服务节点移除(默认90秒)

使用

Eureka Server集群搭建

Eureka集群就是eureka server互相注册、相互守望,先将下面映射写入hosts文件:

127.0.0.1 eureka7001.com
127.0.0.2 eureka7002.com

创建cloud-eureka-server7001cloud-eureka-server7002模块(端口号分别为7001和7002),添加依赖:

<!--eureka-server-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!-- 其他 -->
<dependency>
    <groupId>com.rhett</groupId>
    <artifactId>cloud-api-commons</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.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

yaml配置:

# 端口号,请区分两台机器
server:
  port: 7002
eureka:
  instance:
    hostname: eureka7002.com
  client:
    # false表示不向注册中心注册自己
    register-with-eureka: false
    # false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    fetch-registry: false
    service-url:
      # 设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
      # 7001服务器这里写7002的service-url
      defaultZone: http://eureka7001.com:7001/eureka/

启动类:

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

启动即可

多服务提供者

另外创建一个cloud-provider-payment8002模块,将它和cloud-provider-payment8001的依赖都修改为:

<dependency>
    <groupId>com.rhett</groupId>
    <artifactId>cloud-api-commons</artifactId>
    <version>{project.version}</version>
</dependency>
<!-- 添加eureka client -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</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.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>{druid.spring.boot.starter.version}</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<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>

两个模块的配置:

# 端口号,请区分8001和8002
server:
  port: 8002
spring:
  application:
    name: cloud-payment-service
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # mysql驱动类
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/cloud2020?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password: 123456


mybatis:
  mapperLocations: classpath*:mapper/*.xml
  type-aliases-package: com.rhett.springcloud.entities

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

启动类添加注解:

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

可以修改controller以区分两个提供服务的provider:

@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;

    @PostMapping(value = "/payment")
    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(500,"插入数据库失败");
        }
    }

    @GetMapping(value = "/payment/{id}")
    public CommonResult<Payment> 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(500,"没有对应记录,查询ID:"+id);
        }
    }
}

调用服务

cloud-consumer-order80也要添加依赖:

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

修改获取RestTemplate的配置类:

@Configuration
public class ApplicationContextConfig {
    @Bean
    //启用负载均衡
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

修改controller,替换请求的URL:

@RestController
public class OrderController {
    //public static final String PAYMENT_URL = "http://localhost:8001";
    //这里的CLOUD-PAYMENT-SERVICE是请求的服务在eureka上的名称
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @PostMapping("/consumer/payment")
    public CommonResult<Payment> create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment", payment,CommonResult.class);
    }
    @GetMapping("/consumer/payment/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/"+id,CommonResult.class);
    }
}

可以测试请求consumer的controller,会发现是由不同的服务提供方服务的,并且是交替服务的(轮询)

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/%e6%9c%8d%e5%8a%a1%e6%b3%a8%e5%86%8c%e4%b8%8e%e5%8f%91%e7%8e%b0-eureka%e6%a6%82%e8%bf%b0%e4%b8%8e%e7%ae%80%e5%8d%95%e4%bd%bf%e7%94%a8/

发表评论

电子邮件地址不会被公开。