Eureka学习:搭建Eureka Server、将User Service注册到Eureka Server中

 
更多

在微服务架构中,服务注册与发现是一个非常重要的功能。Eureka作为Netflix开源的一款服务注册中心,为我们提供了方便快捷的服务注册与发现解决方案。本篇博客将介绍如何搭建Eureka Server,并将User Service注册到Eureka Server中。

准备工作

在开始之前,需要确保以下环境已经准备好:

  • JDK 8及以上版本
  • Maven 3.x
  • IDE(推荐使用IntelliJ IDEA)

搭建Eureka Server

  1. 创建一个基于Spring Boot的项目,命名为eureka-server
  2. pom.xml文件中添加以下依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
  1. application.properties文件中添加以下配置:
spring.application.name=eureka-server
server.port=8761

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

eureka.server.enable-self-preservation=false
  1. 创建一个EurekaServerApplication类,并添加@EnableEurekaServer注解,启动Eureka Server:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
  1. 在IDE中运行EurekaServerApplication类,访问http://localhost:8761,可以看到Eureka Server的控制台页面。

注册User Service到Eureka Server

  1. 创建一个基于Spring Boot的项目,命名为user-service
  2. pom.xml文件中添加以下依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  1. application.properties文件中添加以下配置:
spring.application.name=user-service
server.port=8080

eureka.client.service-url.defaultZone=http://localhost:8761/eureka
  1. 创建一个UserController类,并添加@RestController注解,定义一个/users接口:
@RestController
public class UserController {

    @GetMapping("/users")
    public List<String> getUsers() {
        return Arrays.asList("User1", "User2", "User3");
    }
}
  1. UserServiceApplication类上添加@EnableDiscoveryClient注解,启动User Service:
@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }
}
  1. 在IDE中运行UserServiceApplication类,然后访问http://localhost:8080/users,可以看到返回的用户列表。
  2. 再次访问Eureka Server的控制台页面http://localhost:8761,可以看到User Service已成功注册到Eureka Server中。

总结

通过上述步骤,我们成功搭建了Eureka Server,并将User Service注册到了Eureka Server中。Eureka的服务注册与发现功能为我们的微服务架构提供了便利,帮助我们实现了服务的自动化管理。希望本篇博客对您有所帮助,感谢您的阅读!

打赏

本文固定链接: https://www.cxy163.net/archives/8190 | 绝缘体

该日志由 绝缘体.. 于 2020年05月09日 发表在 未分类 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: Eureka学习:搭建Eureka Server、将User Service注册到Eureka Server中 | 绝缘体
关键字: , , , ,

Eureka学习:搭建Eureka Server、将User Service注册到Eureka Server中:等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter