注册微服务,即将服务注册到Eureka服务注册中心
Eureka客户端依赖项添加到服务应用程序的构建中:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>ingredient-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ingredient-service</name>
<description>配料成分微服务</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR6</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
<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>
</project>
applicationl.yml
spring:
application:
name: ingredient-service #设置微服务名称
#默认情况下开发期,Eureka客户端会假定Eureka服务器在本地8761端口上运行,
#但在生产期并非如此,因此我们必需指定Eureka服务器的位置。
#可以指定多个注册服务中心地址,当第一个注册失败时会自动转到第二个进行注册。
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
server:
port: 0 #开发期:设置成任务端口,因为消费者是通过微服务名称查找的,所以端口不需要特别指定。
说明:
spring.application.name:在Eureka中注册服务的名称,设置此属性后,可以通过服务名称myFirstservice2查找服务。
因为你只会通过Eureka查询服务,所以他们正在监听的端口并不重要 - 尤里卡知道他们在哪个端口。因此,为了避免在本地运行时发生潜在的端口冲突,可以将端口设置为0:
eureka.client.service-url属性:需要指定Eureka服务器的位置。这与Eureka服务器配置文件中的地址一至
消费微服务
@RestController
@RequestMapping(path = "/client",produces = "application/json")
@CrossOrigin(origins = "*")
public class IngredientServiceClient {
private RestTemplate rest;
public IngredientServiceClient(@LoadBalanced RestTemplate rest){
this.rest=rest;
}
@GetMapping("/taco")
public Taco getTaco(){
//调用微服务myFirstservice
return rest.getForObject("http://myFirstservice/design/taco",Taco.class);
}
@GetMapping("/mytest")
public String getString(){
return "lsjdlfjlksdjlf";
}
}
@RestController
@RequestMapping(path="design",produces = "application/json")
public class MyserviceController {
@GetMapping(path = "/taco")
public Taco mytest(){
Taco taco=new Taco();
taco.setId(99);
taco.setName("鸡腿汉堡");
taco.setTitle("麦当劳");
return taco;
}
}
@SpringBootApplication
public class MyeurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(MyeurekaClientApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}