springCloud 子服務之間的調用


Springcloud 子服務A的方法

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestAController {

    @RequestMapping("/testA")
    public String TestAController(){
        return "Hello testA";
    }
}

Springcloud 子服務B 調用 子服務A這個方法

首先在服務B創建一個接口如下:服務A的服務名(已eureka中為准)+ 服務A的方法名

 

 以上是注冊中心的服務名稱

package com.example.serviceb.controller;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

//填入注冊中心中的應用名,也就是要調用的微服務的應用名
//在eureka頁面中可以找到
@FeignClient("SERVICE-OBJCAT-A")
public interface ServiceAFeignClient {
    @RequestMapping("testA")
    public String TestAController();
} 

 

再創建一個類進行調用

首先添加注解聲明是注冊中心客戶端@EnableEurekaClient實現不同子服務調用@EnableFeignClients。再將接口注入到此類中進行調用

注:也可在啟動程序上加 @EnableEurekaClient和@EnableFeignClients

 

package com.example.serviceb.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
//添加注解聲明是注冊中心客戶端
@EnableEurekaClient
//實現不同子服務調用
@EnableFeignClients
public class TestBController {
    @Autowired
    private ServiceAFeignClient serviceAFeignClient;

    @RequestMapping("call")
    public String call(){
        String redult = serviceAFeignClient.TestAController();
        return "b to a 訪問結果 ---" + redult;
    }
} 

打印結果:

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM