前言
上一節(jié)我們搭建起了服務(wù)注冊中心镐牺,為各個服務(wù)提供者和消費者提供一個橋梁匹层,這一節(jié)我們搭建一個服務(wù)提供者,注冊到注冊中心
新建eureka-client模塊
代碼結(jié)構(gòu)如下:
代碼編寫
cppba-spring-cloud-eureka-client > pom.xml
<?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">
<modelVersion>4.0.0</modelVersion>
<artifactId>cppba-spring-cloud-eureka-client</artifactId>
<packaging>jar</packaging>
<name>${project.artifactId}</name>
<parent>
<groupId>com.cppba</groupId>
<artifactId>cppba-spring-cloud</artifactId>
<version>1.0.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
</dependencies>
</project>
SpringCloudEurekaClientApplication.java
package com.cppba;
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;
@SpringBootApplication
@EnableEurekaClient
@RestController
public class SpringCloudEurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudEurekaClientApplication.class, args);
}
@Value("${server.port}")
private String port;
@RequestMapping("/hi")
public String sayHi(@RequestParam String name) {
return "hi " + name + ",i am from port:" + port;
}
}
application.properties
server.port=8764
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
spring.application.name=service-say
到此項目搭建完成
啟動項目
啟動eureka-client之前,我們先啟動上一節(jié)搭建的eureka-server,兩個服務(wù)都啟動好以后铐维,我們訪問注冊中心,可以看到:
說明我們服務(wù)注冊成功慎菲!訪問一下http://127.0.0.1:8764/hi?name=hornet
到此嫁蛇,eureka-client(服務(wù)發(fā)現(xiàn))項目搭建成功。
參考項目:https://github.com/bigbeef/cppba-spring-cloud
github地址:https://github.com/bigbeef
個人博客:http://blog.cppba.com