本文介绍生产者服务搭建,并注册到Eureka 注册中心。
相关依赖版本
- spring-boot - 2.1.4.RELEASE
- spring-cloud - Greenwich.SR1
福利 福利 福利!!!
免费领取Java架构技能地图 注意了是免费送
、
免费领取 要的+V 领取

1.Maven依赖
<parent>
<artifactId>spring-could-example</artifactId>
<groupId>com.example</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>server-provider</artifactId>
<description>服务提供者</description>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
1234567891011121314151617181920
2.配置文件
server:
port: 8701
#服务应用名称
spring:
application:
name: server-provider
# 注册中心配置
eureka:
client:
serviceUrl:
# 配置服务注册中心集群时,此处可以配置多个地址(通过逗号隔开)
defaultZone: http://127.0.0.1:7001/eureka/
1234567891011121314
3.启动类 注:需要添加注解 @EnableEurekaClient
/**
* 服务提供者-实例
*
* @author 程序员小强
*/
@EnableEurekaClient
@SpringBootApplication
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
12345678910111213
4.查看注册中心Web页
启动生产者服务后
打开浏览器输入 http://localhost:7001/,可以看到生产者服务已经注册到注册中心了。

5.创建一个测试接口
创建一个测试接口,以便于后续消费者的测试与调试实例展示
/**
* 服务提供者-测试 controller
*
* @author 程序员小强
*/
@RestController
public class TestController {
private static final Logger log = LoggerFactory.getLogger(TestController.class);
@Value("${server.port}")
private String port;
@Value("${spring.application.name}")
private String applicationName;
@RequestMapping("/hello")
public Map<String, Object> hello(@RequestParam(value = "consumerApplicationName", required = false) String consumerApplicationName) {
Map<String, Object> resultMap = new HashMap<>(4);
resultMap.put("code", 200);
resultMap.put("messages", "成功");
//生产者服务启动端口
resultMap.put("providerServerPort", port);
//生产者服务名称
resultMap.put("providerApplicationName", applicationName);
//消费者服务名称
resultMap.put("consumerApplicationName", consumerApplicationName);
log.info(" [ 服务生产者 {} ] >> hello method end , reqApplicationName:{} , resultMap:{}", applicationName, consumerApplicationName, resultMap);
return resultMap;
}
}