您的位置:首页 > 编程语言 > Java开发

SpringCloud-2-Eureka将服务注册到Eureka

2018-02-01 15:59 375 查看
基于上一篇文章已创建好服务发现和注册中心,现在我们新搞一个服务提供者并将提供的服务注册到Eureka.

首页也是从POM开始,引入Eureka依赖.

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build> 然后在我们的启动类上添加Eureka的客户端注解,标识这是一个Eureka客户端.
@SpringBootApplication
@@EnableDiscoveryClient//启动一个服务供消费者调用
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
注意客户端 和 服务端 的注解区分  @EnableDiscoveryClient  @EnableEurekaServer

这个服务如何注册到服务端去呢,添加我们的配置.application.properties.
#注册端口号
server.port=8762
#注册名称
spring.application.name=SERVICE-HELLO
#注册地址
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka
# 心跳时间,即服务续约间隔时间(缺省为30s)
eureka.instance.lease-renewal-interval-in-seconds=5
# 发呆时间,即服务续约到期时间(缺省为90s)
eureka.instance.lease-expiration-duration-in-seconds=10解释下server.port=8762 为本服务暴露端口,
spring.application.name 注册的应用(服务名称ID)

eureka.client.serviceUrl.defaultZone Eureka服务中心的地址.

既然是服务提供方,肯定要提供具体服务了.接下来写个具体的方法作为服务提供吧.新搞个Controller ,提供方法

@Value("${server.port}")
private int serverPort = 0;

@RequestMapping(value = "/hello")
@ResponseBody
public String sayHello() {
return "Hello, Spring Cloud! My port is " + String.valueOf(serverPort);
}OK 需要提供的服务就一个简单的hello 并返回提供服务者的端口号,用来区分是哪个服务提供的.运行我们的项目,在去查看服务控制中心的页面有什么区别呢.


DS Replicas


Instances currently registered with Eureka

ApplicationAMIsAvailability ZonesStatus
SERVICE-HELLOn/a (1)(1)UP (1) - localhost:SERVICE-HELLO:8762
这个地方会冒出这么一个玩意儿来,这就是我们新注册上去的服务啦.好了,服务是提供上去了,下面我们搞个消费者上去消费一下.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息