第四篇:服务治理:Spring Cloud Eureka——注册服务提供者

1、新建一个项目:hello-service

注意版本信息是否正确。

2、引入相应依赖

3、创建controller

package com.example.helloservice.web;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    private final Logger log=Logger.getLogger(getClass());
    //通过DiscoveryClient对象在日志中打印出服务的相关内容
    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value="/hello",method = RequestMethod.GET)
    public String hello(){
        ServiceInstance instance=client.getLocalServiceInstance();
        log.info("/hello,host:"+instance.getHost()+",service_id:"+instance.getServiceId());
        return "Hello Word";
    }
}

2、在主类中加注解@EnableDiscoveryClient

package com.example.helloservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class HelloServiceApplication {

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

3、在application.properties中配置

server.port=8091
spring.application.name=hello-service
#指定服务注册中心的地址
eureka.client.service-url.defaultZone=http://localhost:8081/eureka

4、启动两个项目,会在http://localhost:8081/看到

 

5、总结:

服务注册中心使用注解:@EnableEurekaServer

服务提供者使用注解:@EnableDiscoveryClient

指定服务注册中心地址需配置:eureka.client.service-url.defaultZone=http://localhost:8081/eureka

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值