如何使用Eureka注册服务

1.创建一个maven父工程microservice-springcloud,并在工程的pom.xml中添加spring cloud的版本依赖信息。

<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

2.搭建服务端工程

在父工程microservice-springcloud中,创建Maven子模块microservice-eureka-server作为服务端工程,该模块是一个基础的spring boot工程。

<1>添加依赖

<2>编写配置文件

<3>修改客户端java代码

详细:

<1>添加依赖。pom.xml中

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

<2>编写配置文件。在配置文件中增加端口号等配置信息。

spring:
  port:8761

eureka:
  instance:
    hostname:localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://registry:8761/eureka/

上述代码中,首先配置了端口号为8761,所有服务的实例都需要向此端口注册。接下来配置了实例名为localhost。由于本项目是一个注册中心,是不需要向自己注册和检索服务的,所以 registerWithEureka和   fetchRegistry都需要设置为false。最后defaultZone中的地址是注册中心的地址。

<3>修改服务端java代码。在项目的引导类上添加注解@EnableEurekaServer,该注解用于标注类是一个Eureka Server。

@SpringBootApplication
@EnableEurekaServer
public class RegistryApplication {

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

<4>启动应用,查看信息。完成上述配置后,启动应用程序并在浏览器中访问地址http://localhost:8761,即可看到Eureka的信息面板。

 

3.搭建客户端工程

在父工程中创建maven子模块microservice-eureka-user作为客户端工程,该模块也是一个基础的spring boot工程。

<1>添加依赖

<2>编写配置文件

<3>修改客户端java代码

详细:

<1>添加依赖。pom.xml中

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

<2>编写配置文件

server:
  port:8000  #指定该Eureka实例的端口号

eureka:
  instance:
    prefe-ip-address:true   #是否显示主机的IP
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://registry:8761/eureka/ #指定Eureka服务端地址
spring:
    application:
        name:microservice-eureka-user  #模块的名称

<3>修改客户端java代码

@SpringBootApplication
@EnableEurekaClient
@RestController
public class AccountApplication {

    @RequestMapping("/hello")
    public String home(){
        return "hello world";
    }
	public static void main(String[] args) {
		SpringApplication.run(AccountApplication.class, args);
	}

}

<4>启动应用。服务会注册到应用中心,注册后的服务就可以直接被其他服务调用。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值