版权声明:本文为博主原创文章,觉得稍有帮助,可点赞、转载注明出处。 https://blog.csdn.net/chenghuaying/article/details/82694676
1. 简介
上篇记录了如何启动一个服务注册中心,本篇记录如何发布一个服务,并将服务注册到注册中心。服务的发布是当一个服务功能完成,启动并开始处理请求。服务注册是将服务的相关信息注册到注册中心,便于服务调用者通过注册中心发现服务,进而调用服务。
2. 代码实现
2.1涉及的模块
- eureka-server-singleton:服务注册中心
- eureka-service:服务提供者
2.2 源代码
2.2.1 Github地址
https://github.com/andyChenHuaYing/spring-cloud-demo
2.2.2 切换
Commit:Finished eureka-service
Revision Number:e1489c1e17e83e620177df7ae17b5194d0151452
spring-cloud-demo目录下,终端执行命令:
git checkout e1489c1e17e83e620177df7ae17b5194d0151452
2.3 eureka-service
2.3.1 pom文件添加依赖
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-finchley-demo</artifactId>
<groupId>org.oscar.scd</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>eureka-service</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
</project>
2.3.2 application.yml
指定注册中心地址,当前服务application name以及端口8762
server:
port: 8762
spring:
application:
name: eureka-service
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
2.3.3 EurekaServiceApplication
实例方法应返回spring.application.name + : + server.port更加直观,后续统一优化
package org.oscar.scd.eureka.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableEurekaClient
@SpringBootApplication
public class EurekaServiceApplication {
@Value("${server.port}")
private int serverPort;
@RequestMapping("/print")
public String serverPortPrint(@RequestParam(value = "name", defaultValue = "oscar") String name) {
return "Hi " + name + " ,i am from port: " + serverPort;
}
public static void main(String[] args) {
SpringApplication.run(EurekaServiceApplication.class, args);
}
}
3. 验证
3.1 启动模块
- 启动服务注册中心
- 启动服务提供者
3.2 访问服务信息界面
访问地址:http://localhost:8761/
查看已注册的服务,名称为eureka-service。
4. 思考
- 网络连接:基于http协议,是否还有其他方式
- 数据传输:目前只支持http形式的通讯,是否支持其他的通讯方式如RPC
- 数据协议:是否支持多种协议,如json,hession等
5. 补充
5.1 资料
http://cloud.spring.io/spring-cloud-static/Finchley.SR1/multi/multi_spring-cloud-eureka-server.html