Spring-Cloud-Eureka-Client

本文详细介绍了如何配置Spring Cloud Eureka客户端,包括一个仅提供服务的模块和一个同时提供服务并调用其他服务的模块。提供了POM配置、application.yml设置以及启动类代码。服务消费方式包括Feign和Ribbon,其中Feign通过接口调用,Ribbon使用@LoadBalanced的RestTemplate。还讨论了Ribbon的负载均衡策略,如轮询、随机等,并展示了如何自定义策略。

1.Eureka-server就是一个注册中心,其他的Eureka-Client都是一个个的微服务,彼此间相互调用。
2.服务的提供仅仅需要引用spring-cloud-starter-netflix-eureka-client
3.服务的消费方式
1):feign,一个通过本地接口的形式来进行调用服务的,其中Feign中默认引入了Ribbon,以接口的形式进行调用服务,看起来简洁,而且Feign中还可以增加熔断器,来进行服务的熔断和降级,防止服务调用中的服务的雪崩
需要引用spring-cloud-starter-netflix-eureka-client和spring-cloud-starter-openfeign,
spring-cloud-starter-netflix-eureka-client讲此模块注册到Eureka-server
spring-cloud-starter-openfeign,调用远程的服务
2):ribbon,一个基于Http端的负载均衡,通过在Configuration中配置RestTemplate来进行调用,可以自定义负载均衡的方式,需要在配置Bean:RestTemplate时加上@LoadBalanced

一个仅仅提供服务的模块(不调用其他的服务)

POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-clould-Official</artifactId>
        <groupId>com.wx</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Eureka-Client</artifactId>

    <dependencies>
        <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>
    </dependencies>

</project>

功效备注:

spring-cloud-starter-netflix-eureka-client

声明这是一个eureka客户端,要注册到eureka的服务之一

spring-boot-starter-web

使用@RestController等等注解,搭建MVC系统

spring-boot-starter-actuator

服务健康检查

application.yml


eureka:
  client:
    serviceUrl:
      defaultZone: http://192.168.88.1:8761/eureka/
    healthcheck:
      enabled: true
#   By default, the EurekaClient bean is refreshable, meaning the Eureka client properties can be changed and refreshed. When a refresh occurs clients will be unregistered from the Eureka server and there might be a brief moment of time where all instance of a given service are not available. One way to eliminate this from happening is to disable the ability to refresh Eureka clients. To do this set eureka.client.refresh.enable=false.
    refresh:
      enable: false
  instance:
    instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
    leaseRenewalIntervalInSeconds: 30
server:
  port: 9001

spring:
  application:
    name: client01


EurekaCliApplication01.java(启动类)

package com.wx.client01;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

@SpringBootApplication
//EnableEurekaClient可省略
//@EnableEurekaClient
public class EurekaCliApplication01 {

    public static void main(String[] args) {
        new SpringApplicationBuilder(EurekaCliApplication01.class).web(true).run(args);
    }
}

提供的服务

package com.wx.client01.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping("/sayhi")
    public String sayHi(@RequestParam(value = "name" ,defaultValue = "Lin") String name){
        return "Hi,"+name;
    }
}

一个既可以提供服务,又可以调用其他服务的模块

POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-clould-Official</artifactId>
        <groupId>com.wx</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Eureka-Client-02</artifactId>
    <dependencies>
        <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.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>

</project>

application.yml

server:
  port: 9002

eureka:
  client:
    serviceUrl:
      defaultZone: http://192.168.88.1:8761/eureka/
    healthcheck:
      enabled: true
#   By default, the EurekaClient bean is refreshable, meaning the Eureka client properties can be changed and refreshed. When a refresh occurs clients will be unregistered from the Eureka server and there might be a brief moment of time where all instance of a given service are not available. One way to eliminate this from happening is to disable the ability to refresh Eureka clients. To do this set eureka.client.refresh.enable=false.
    refresh:
      enable: false
  instance:
    instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
    leaseRenewalIntervalInSeconds: 30

spring:
  application:
    name: client01


启动类

package com.wx.client01;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
//EnableEurekaClient可省略
//@EnableEurekaClient
@EnableFeignClients
public class EurekaCliApplication02 {

    public static void main(String[] args) {
        new SpringApplicationBuilder(EurekaCliApplication02.class).web(true).run(args);
    }
}

MVC view

package com.wx.client01.controller;

import com.wx.client01.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class HelloController {
    @Autowired
    private HelloService helloService;

    @RequestMapping("/sayhi")
    public String sayHi(@RequestParam(value = "name" ,defaultValue = "opopopop") String name){

        return helloService.sayHi(name);
    }
}

feign 调用远程服务

package com.wx.client01.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Service
@FeignClient(value = "client01",name = "client01")
public interface HelloService {

    @RequestMapping(value = "/hello/sayhi")
    public String sayHi(@RequestParam("name") String name);

}

Ribbon调用

1.@LoadBalanced配置RestTemplate(没有@LoadBalanced会报错找不到主机)
package com.wx.client02.config;

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;

@Configuration
public class RestTemplateConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

2.调用
package com.wx.client02.controller;

import com.wx.client02.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/hello")
public class HelloController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/sayRest/{name}")
    public String sayRest(@PathVariable("name") String name){
        String serviceRest = restTemplate.getForObject("http://client01/hello/sayhi?name=" + name, String.class);
        return serviceRest;
    }
}

3.Ribbon 自带的负载均衡策略
  • RoundRobinRule:轮询。
  • RandomRule:随机。
  • AvailabilityFilteringRule:先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,以及并发连接数超过阈值的服务,剩下的服务,使用轮询策略。
  • WeightedResponseTimeRule:根据平均响应时间计算所有服务的权重,响应越快的服务权重越高,越容易被选中。一开始启动时,统计信息不足的情况下,使用轮询。
  • RetryRule:先轮询,如果获取失败则在指定时间内重试,重新轮询可用的服务。
  • BestAvailableRule:先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务。
  • ZoneAvoidanceRule:复合判断 server 所在区域的性能和 server 的可用性选择服务器
使用方法 new 相应的策略即可
package com.wx.client02.config;

import com.netflix.loadbalancer.RandomRule;
import com.netflix.loadbalancer.RoundRobinRule;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration;
import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Configuration
public class RestTemplateConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    @Bean
    public RoundRobinRule randomRule(){
        return new RoundRobinRule();
    }


}

### 使用 `spring-cloud-starter-netflix-eureka-client` 的方法 #### Maven 配置 为了正确引入 `spring-cloud-starter-netflix-eureka-client`,需要在项目的 `pom.xml` 文件中配置 Spring Cloud 的依赖管理部分。以下是推荐的配置方式: ```xml <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Greenwich.SR1</version> <!-- 版本号需根据实际需求调整 --> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies> ``` 上述配置通过 `spring-cloud-dependencies` 来统一管理 Spring Cloud 组件的版本,从而避免因手动指定不同组件版本而导致的冲突问题[^3]。 --- #### 启用 Eureka 客户端功能 要在应用程序中启用 Eureka 客户端的功能,需要完成以下操作: 1. **修改 `application.yml` 或 `application.properties`** 添加必要的配置项来连接到 Eureka Server 实例。例如,在 `application.yml` 中可以这样设置: ```yaml eureka: client: service-url: defaultZone: http://localhost:1010/eureka/ # 替换为实际的Eureka服务器地址 ``` 2. **标注主类** 在 Spring Boot 应用程序的入口类上添加 `@EnableDiscoveryClient` 注解,以便让应用注册到 Eureka 服务发现机制中。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` --- #### 常见问题及其解决办法 1. **无法解析依赖问题** 如果遇到类似于 “Cannot resolve org.springframework.cloud:spring-cloud-starter-netflix-eureka-client” 的错误,可能是由于网络原因导致某些依赖未能成功下载。可以通过清理本地 Maven 缓存并强制重新加载依赖来解决问题[^5]。具体步骤如下: - 打开终端,进入 `.m2/repository` 目录; - 删除所有带有 `.lastUpdated` 后缀的文件; - 返回 IDE 并刷新项目(通常可通过右键点击项目 -> Reload Project)。 2. **版本冲突** 当多个模块之间存在不兼容的版本时,可能会引发运行时异常或编译失败。建议始终使用一致的 BOM(Bill of Materials),即通过 `spring-cloud-dependencies` 进行全局版本控制[^2]。 3. **Eureka Client 未正常注册** 若客户端未能成功向 Eureka Server 注册,则可能是因为 `defaultZone` 地址配置有误或者 Eureka Server 尚未启动。确认两者之间的连通性以及日志中的提示信息有助于定位问题所在[^4]。 --- ### 示例代码片段 下面是一个简单的微服务实例,展示如何利用 Eureka 客户端实现服务注册与发现: ```java @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello from Eureka Client!"; } } ``` 当此服务启动后,它会自动尝试联系已定义好的 Eureka Server,并将自己的元数据提交上去供其他消费者调用。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值