• 【SpringCloud】Eureka注册中心 代码详细介绍


    Eureka是Spring Cloud的服务发现和注册中心,它提供了服务注册和发现的功能,使得服务消费者可以自动发现服务提供者并进行调用。下面是一个简单的Eureka注册中心的代码示例,并进行详细介绍。

    首先,需要在Spring Boot项目中添加Eureka Server的依赖。在pom.xml文件中添加以下依赖:

    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4

    接下来,创建Eureka Server的配置类,通常放在@SpringBootApplication标注的主类同级或子包下,并使用@EnableEurekaServer注解启用Eureka Server:

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
    
    @SpringBootApplication
    @EnableEurekaServer
    public class EurekaServerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(EurekaServerApplication.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    application.ymlapplication.properties中配置Eureka Server的属性:

    server:
      port: 8761 # Eureka Server的端口号
    
    eureka:
      instance:
        hostname: localhost # Eureka Server的主机名
      client:
        registerWithEureka: false # 是否将自己注册到Eureka Server,默认为true,因为是Server,所以这里设置为false
        fetchRegistry: false # 是否从Eureka Server获取注册信息,默认为true,因为是Server,所以这里设置为false
        serviceUrl:
          defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ # Eureka Server的地址
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    以上配置指定了Eureka Server运行在8761端口,并且关闭了自我注册和从其他Eureka Server获取注册信息的功能,因为当前实例就是Eureka Server本身。defaultZone定义了Eureka客户端注册和发现服务时应该使用的地址。

    启动Eureka Server的main方法,你会看到控制台输出Eureka Server启动的日志,并且可以通过访问http://localhost:8761/来查看Eureka Server的管理界面。

    服务提供者(生产者)需要将自身注册到Eureka Server上,以便服务消费者(调用者)能够发现它们。在服务提供者的配置中,需要添加Eureka Client的依赖,并配置eureka.client.serviceUrl.defaultZone指向Eureka Server的地址。

    服务消费者同样需要添加Eureka Client的依赖,并配置Eureka Server的地址。Spring Cloud会利用Eureka Client的自动配置功能,自动从Eureka Server获取服务提供者的列表,并通过服务发现机制找到正确的服务实例进行调用。

    这只是一个简单的Eureka注册中心的代码示例和配置。在实际生产环境中,你可能还需要考虑Eureka Server的集群部署、安全性配置、持久化存储等问题。Spring Cloud提供了丰富的配置选项和扩展点,以满足各种复杂场景的需求。

  • 相关阅读:
    SpringCloud 微服务全栈体系(三)
    docker部署lnmp环境
    vue实战-mockjs模拟数据
    保姆级深度学习环境搭建(亲测避坑)
    C语言文件操作
    基于SSM框架的人力资源管理系统毕业设计源码060936
    深信服实验 | AF做透明部署时,如何对上网数据进行基本的上网管控和防护?
    (论文阅读31/100)Stacked hourglass networks for human pose estimation
    23中设计模式之访问者visitor设计模式
    【Docker】本地镜像与私有库:发布、拉取,图文展示全过程
  • 原文地址:https://blog.csdn.net/weixin_43784341/article/details/137255359