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