springcloud(三):服務提供與調用

上一篇文章咱們介紹了eureka服務註冊中心的搭建,這篇文章介紹一下如何使用eureka服務註冊中心,搭建一個簡單的服務端註冊服務,客戶端去調用服務使用的案例。java

案例中有三個角色:服務註冊中心、服務提供者、服務消費者,其中服務註冊中心就是咱們上一篇的eureka單機版啓動既可,流程是首先啓動註冊中心,服務提供者生產服務並註冊到服務中心中,消費者從服務中心中獲取服務並執行。spring

服務提供

咱們假設服務提供者有一個hello方法,能夠根據傳入的參數,提供輸出「hello xxx,this is first messge」的服務springboot

一、pom包配置

建立一個springboot項目,pom.xml中添加以下配置:app

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

二、配置文件

application.properties配置以下:框架

spring.application.name=spring-cloud-producer
server.port=9000
eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/

參數在上一篇都已經解釋過,這裏很少說。spring-boot

三、啓動類

啓動類中添加@EnableDiscoveryClient註解this

@SpringBootApplication
@EnableDiscoveryClient
public class ProducerApplication {

	public static void main(String[] args) {
		SpringApplication.run(ProducerApplication.class, args);
	}
}

四、controller

提供hello服務spa

@RestController
public class HelloController {
	
    @RequestMapping("/hello")
    public String index(@RequestParam String name) {
        return "hello "+name+",this is first messge";
    }
}

添加@EnableDiscoveryClient註解後,項目就具備了服務註冊的功能。啓動工程後,就能夠在註冊中心的頁面看到SPRING-CLOUD-PRODUCER服務。code

到此服務提供者配置就完成了。server

願意瞭解框架技術或者源碼的朋友直接求求交流分享技術:貳一四七七七五六叄叄

相關文章
相關標籤/搜索