首页 > 其他分享 >Spring Cloud 系列之 Eureka 实现服务注册与发现

Spring Cloud 系列之 Eureka 实现服务注册与发现

时间:2023-04-28 17:34:51浏览次数:51  
标签:String spring Eureka Cloud Spring eureka public cloud

如果你对 Spring Cloud 体系还不是很了解,可以先读一下 Spring Cloud 都有哪些模块

Eureka 是 Netflix 开源的服务注册发现组件,服务发现可以说是微服务架构的核心功能了,微服务部署之后,一定要有服务注册和发现的能力,Eureka 就是担任这个角色的。如果你用过 dubbo 的话,那一定知道 dubbo 中服务注册和发现的功能是用 zookeeper 来实现的。

Eureka 目前是 2.x 版本,并且官方已经宣布不再维护更新。不过其实 Eureka 已经很稳定了,当做注册中心完全没有问题。Spring Cloud 集成了 Eureka ,并做了完善的封装。方便我们使用 Spring boot 开发的时候简单配置就可以使用。

微服务框架中有三类角色,分别是注册中心、服务提供者、服务消费者,注册中心就是今天要说的主角 Eureka,这篇文章简单说明 Spring Cloud Eureka 的使用,模拟实现单点和高可用注册中心,并简单介绍服务提供者和服务消费者如何使用 Eureka 提供的服务注册和发现功能。

版本说明
Java : 1.8

Spring Boot : 2.1.3.RELEASE

Spring Cloud: Finchley.SR2

之说以要说一下版本,因为 Finchley.SR2 版本较之前的版本包名有变化,所以在引用 maven 包的时候要注意。

单点注册中心

创建 Eureka 注册中心

1、引用 maven 包,其中

<dependencyManagement> 
  <dependencies> 
    <dependency> 
      <groupId>org.springframework.cloud</groupId>  
      <artifactId>spring-cloud-dependencies</artifactId>  
      <version>Finchley.SR2</version>  
      <type>pom</type>  
      <scope>import</scope> 
    </dependency> 
  </dependencies> 
</dependencyManagement>

<!-- 最新版的 eureka 服务端包 -->
<dependency> 
  <groupId>org.springframework.cloud</groupId>  
  <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> 
</dependency>

<!-- 监控管理 -->
<dependency> 
  <groupId>org.springframework.boot</groupId>  
  <artifactId>spring-boot-starter-actuator</artifactId> 
</dependency>

2、新建 bootstrap.yml,并配置 Spring cloud 参数

spring:
  application:
    name: kite-eureka-center
  cloud:
    inetutils: ## 网卡设置
      ignoredInterfaces:  ## 忽略的网卡
        - docker0
        - veth.*
        - VM.*
      preferredNetworks:  ## 优先的网段
        - 192.168

3、新建 application.yml ,并配置参数

server:
  port: 3000
eureka:
  instance:
    hostname: eureka-center
    appname: 注册中心
  client:
    registerWithEureka: false # 单点的时候设置为 false 禁止注册自身
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://localhost:3000/eureka
  server:
    enableSelfPreservation: false
    evictionIntervalTimerInMs: 4000

bootstrap.yml 和 application.yml 的区别:

  • bootstrap.yml 在 application.yml 之前启动;
  • bootstrap.yml 配置 application 的 name、spring.cloud.config.server.git.uri、一些encryption/decryption(加密/解密)信息;
  • application.yml 的信息会覆盖 bootstrap.yml 中的内容,当遇到相同的配置的时候;

4、新建 Application.java 启动文件

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

@EnableEurekaServer 表示使用 Eureka Server 端功能,也就是启动为一个注册中心节点。

5、运行 Application.java ,访问 http://localhost:3000 即可看到 Eureka 提供的 ui 控制台。

Spring Cloud 系列之 Eureka 实现服务注册与发现_Spring Cloud

创建一个服务提供者

接下来创建一个服务提供者,并注册到上面创建的 Eureka 注册中心。

1、添加 maven 依赖包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- eureka 客户端 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

2、配置 application.yml

server:
  port: 3001

eureka:
  instance:
    preferIpAddress: true
  client:
    serviceUrl:
      defaultZone: http://localhost:3000/eureka  ## 注册到 eureka 
spring:
  application:
    name: single-provider  ## 应用程序名称,后面会在消费者中用到

3、创建一个简单的 RESTful 接口 controller

@Slf4j
@RestController
public class ProviderController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "/hello")
    public String hello(){
        List<String> services = discoveryClient.getServices();
        for(String s : services){
            log.info(s);
        }
        return "hello spring cloud!";
    }

    @RequestMapping(value = "/nice")
    public String nice(){
        List<String> services = discoveryClient.getServices();
        for(String s : services){
            log.info("gogogo" + s);
        }
        return "nice to meet you!";
    }

}

4、创建 spring boot 启动类

@EnableEurekaClient
@SpringBootApplication
public class SingleProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(SingleProviderApplication.class, args);
    }
}

@EnableEurekaClient 修饰,表示要注册到注册中心。

5、启动项目,正常情况下就注册到了 Eureka 注册中心,打开 Eureka 控制台,会看到已经出现了这个服务

Spring Cloud 系列之 Eureka 实现服务注册与发现_服务注册_02

创建一个服务消费者

有了服务提供者,接下来创建一个消费者来消费一下

1、引用 maven 包

<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.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2、配置 application.yml

server:
  port: 3002
eureka:
  client:
    serviceUrl:
      defaultZone: http://127.0.0.1:3000/eureka  ## 注册到 eureka
  instance:
    preferIpAddress: true
spring:
  application:
    name: single-customer

3、开始消费提供者提供的服务接口,这里演示了两种消费方法,一种是用 RestTemplate ,另外一种是用 FeignClient,Feign 同样是 Netflix 开源,并被 Spring Cloud 封装到 spring-cloud-starter-openfeign 包中。

创建启动类,并添加相关注解

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class SingleCustomerApplication {

    /**
     * 注入 RestTemplate 
     * 并用 @LoadBalanced 注解,用负载均衡策略请求服务提供者
     * 这是 Spring Ribbon 的提供的能力
     * @return
     */
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(SingleCustomerApplication.class, args);
    }
}

@EnableEurekaClient 声明此项目为一个 eureka 客户端,@EnableFeignClients 声明此项目可以使用 Feign。

4、创建一个服务接口类,这是 Feign 的使用方式,详细的用法可以查一下 Spring Cloud Feign 相关文档

/**
 * IHelloService
 * 配置服务提供者:single-provider 是服务提供者的 application.name
 */
@FeignClient("single-provider")
public interface IHelloService {

    @RequestMapping(value = "/hello")
    String hello();

    @RequestMapping(value = "nice")
    String nice();
}

@FeignClient 注解的 value 为服务提供者的 appplication.name 。

5、创建一个 Controller 用于调用服务

@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IHelloService helloService;

    private static final String applicationName = "single-provider";

    @RequestMapping(value = "feignRequest")
    public Object feignRequest(){
        String s = helloService.nice();
        return s;
    }

    @RequestMapping(value = "commonRequest")
    public Object commonRequest(){
        String url = "http://"+ applicationName +"/hello";
        String s = restTemplate.getForObject(url,String.class);
        return s;
    }

}

其中 feignRequest 方法是使用了 Feign 的方式调用服务接口;

commonRequest 方法是用 RestTemplate 提供的方法调用服务接口;

6、最后,启动服务,访问地址:http://localhost:3002/commonRequest 和 http://localhost:3002/feignRequest

获取源码

如果你觉得写的还可以的话,请点个「推荐」吧

欢迎关注,不定期更新本系列和其他文章

古时的风筝 ,进入公众号可以加入交流群

Spring Cloud 系列之 Eureka 实现服务注册与发现_spring_03

人生没有回头路,珍惜当下。



标签:String,spring,Eureka,Cloud,Spring,eureka,public,cloud
From: https://blog.51cto.com/u_15717245/6235033

相关文章

  • Spring 实现自定义 bean 的扩展
    Springmvc提供了扩展xml的机制,用来编写自定义的xmlbean,例如dubbo框架,就利用这个机制实现了好多的dubbobean,比如 <dubbo:application>、<dubbo:registry> 等等,只要安装这个标准的扩展方式实现配置即可。扩展自定义bean的意义何在假设我们要使用一个开源框架或者一套......
  • 你一直在用的 Spring Boot Starters 究竟是怎么回事
    SpringBoot对比SpringMVC最大的优点就是使用简单,约定大于配置。不会像之前用SpringMVC的时候,时不时被xml配置文件搞的晕头转向,冷不防还因为xml配置上的一点疏忽,导致整个项目莫名其妙的不可用,顿感生活无所依恋,简称生无可恋。这要归功于组成了SpringBoot的各种各样的......
  • Spring AOP 和 动态代理技术
     AOP是什么东西首先来说AOP并不是Spring框架的核心技术之一,AOP全称AspectOrientProgramming,即面向切面的编程。其要解决的问题就是在不改变源代码的情况下,实现对逻辑功能的修改。常用的场景包括记录日志、异常处理、性能监控、安全控制(例如拦截器)等,总结起来就是,凡是想对......
  • vscode下搭建springboot
    安装两个扩展JavaExtensionforPackSpringBootExtensionPack配置mavenctrl+,搜索java.configuration.maven输入setting.xml的路径注意路径不能有中文或者空格创建springboot项目ctrl+shift+p创建项目,输入springbootInitializer即可。参考博客vscode配置ma......
  • Spring源码分析之BeanFactory
    概述以XmlBeanFactory为例分析Xml描述的Bean被Reasource加载到内存,先解析为Document对象,再解析为BeanDefinition注册到BeanDefinitionRegistry,再通过BeanFactory创建名词解释Resource是Spring对资源的抽象,主要是用来读取文件输入流Document是java本身的API进行解析的,得到......
  • 【专栏精选】实战:使用LeanCloud上传玩家分数,实现排行榜
    本文节选自洪流学堂公众号技术专栏《大话Unity2019》,未经允许不可转载。洪流学堂公众号回复专栏,查看更多专栏文章。洪流学堂,让你快人几步。你好,我是郑洪智。小新:“有了用户登录后,我们总要拿来做点什么事情吧?”大智:“有了用户登陆信息之后,就可以针对用户来存储他自己的信息了,比如......
  • 【专栏精选】使用LeanCloud实现玩家登陆
    本文节选自洪流学堂公众号技术专栏《大话Unity2019》,未经允许不可转载。洪流学堂公众号回复专栏,查看更多专栏文章。洪流学堂,让你快人几步。你好,我是郑洪智。小新:“今天我们是不是该学习登陆了?”大智:“没错,不过登陆我不准备给你讲,你自己学,有啥问题再问我。”小新:“好的吧,正好考验......
  • Spring XML配置的12个技巧
    Spring是一个强有力的java程序框架,其被广泛应用于java的程序中。它用POJO提供了企业级服务。Spring利用依赖注入可以获得简单而有效的测试能力。Springbeans,依赖关系,以及服务所需要的bean都将在配置文件中予以描述,配置文件一般采用XML格式。然而XML配置文件冗长而不易使用,在你进......
  • springcloud gateway filter 重写response
     importorg.reactivestreams.Publisher;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.cloud.gateway.filter.GatewayFilterChain;importorg.springframework.cloud.gateway.filter.GlobalFilter;importorg.springfram......
  • Maven指令打包SpringBoot项目提示没有主清单文件
    Maven指令打包SpringBoot项目提示没有主清单文件原文链接:https://blog.csdn.net/greedystar/article/details/86068314项目打包为Jar后,通过java-jarxxxxx.jar运行时提示xxxxx.jar中没有主清单属性,如下:打开jar包,META-INF目录下的MANIFEST.MF,内容如下:Manifest-Version:1.0A......