- 新建项目
添加依赖
4.0.0 org.springframework.boot spring-boot-starter-parent 2.5.5 com.example demo 0.0.1-SNAPSHOT Eureka Provider Demo Demo project for Spring Boot 1.8 2020.0.4 org.springframework.boot spring-boot-starter org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import org.apache.maven.plugins maven-resources-plugin 3.1.0 org.springframework.boot spring-boot-maven-plugin
添加配置application.properties
#应用的名称 spring.application.name=provider #应用的端口号 server.port=8000 provider.name=provider0 #“服务中心”的地址 eureka.client.serviceUrl.defaultZone=http://node1:8081/eureka/,http://node2:8082/eureka/,http://node3:8083/eureka/
启用注册和发现
在启动类中添加注解@EnableDiscoveryClient
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
//启用客户端的服务注册和发现功能
@EnableDiscoveryClient
public class EurekaProviderDemoApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaProviderDemoApplication.class, args);
}
}
实现“服务提供者”接口
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//服务接口
@RestController
public class HelloController {
//注入“服务提供者”的名称
@Value("${provider.name}")
private String name;
//注入“服务提供者”的端口
@Value("${server.port}")
private String port;
//提供的接口,用于返回信息
@RequestMapping("/hello")
public String hello(){
String str = "provider="+name+" port="+port;
//返回数据
return str;
}
}
##TODO
- @Value注解获取配置信息的方法
检查服务有效性
clean->package
java -jar demo-0.0.1-SNAPSHOT.jar
看“服务中心”中instances currently registered with Eureka是否出现了服务?
通过:http://node1:8081/查看返回结果是否如下,是则说明接口正在正常工作。
添加配置application-provider1.properties
#应用的名称 spring.application.name=provider #应用的端口号 server.port=8001 provider.name=provider1 #“服务中心”的地址 eureka.client.serviceUrl.defaultZone=http://node1:8081/eureka/,http://node2:8082/eureka/,http://node3:8083/eureka/
添加配置application-provider2.properties
#应用的名称 spring.application.name=provider #应用的端口号 server.port=8002 provider.name=provider2 #“服务中心”的地址 eureka.client.serviceUrl.defaultZone=http://node1:8081/eureka/,http://node2:8082/eureka/,http://node3:8083/eureka/
cmd
java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=provider1
cmd
java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=provider2



