spring cloud腳手架項目(三)feign接口調用

前言

在結束技術選擇和模塊化項目搭建之後。我們的spring boot項目就可以啓動了。這時候就需要聊到微服務的一個重大作用,RPC調用
文章參考:
feign問題處理:http://www.imooc.com/article/289005
如何調用feign:https://segmentfault.com/a/1190000012496398

feign

feign接口調用是spring cloud下常用的RPC調用,自帶Spring Cloud Ribbon 與 Spring Cloud Hystrix,提供了方便的負載均衡和斷融,降級等服務

代碼

pom文件

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

Service文件

import com.chen.service.requestDTO.TestHelloRequestDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;


@FeignClient(name = "SERVICE-A")
//@FeignClient註解value必須與服務客戶端application.yml配置中服務命名對應
public interface TestService {
    @RequestMapping("/hello")
    public String hello(TestHelloRequestDTO requestDTO);
    @RequestMapping("/hi")
    public String hi();
}

serviceimpl文件

import com.alibaba.fastjson.JSON;
import com.chen.service.requestDTO.TestHelloRequestDTO;
import com.chen.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@Slf4j
@RestController
public class TestServiceImpl implements TestService {

    @Override
    public String hello(@RequestBody TestHelloRequestDTO requestDTO) {
        log.info(JSON.toJSONString(requestDTO));
        return "hello";
    }

    @Override
    public String hi() {
        return "hi";
    }

}

啓動類註解

@SpringBootApplication
//Spring boot啓動類
@EnableEurekaClient
//eureka 註冊類
@RestController
//一個spring mvc控制
@EnableDiscoveryClient
//eureka 發現
@EnableFeignClients(basePackages = {"com.chen.service"})
//feign包掃描

使用

坑點:
1.spring cloud feign接口無法調用。接口404或者調用後500,因爲我把啓動類的位置調整了。我們的默認包爲com.chen.xxx,則啓動類要放在com.chen下面
2.項目啓動失敗,原因有二,一是@FeignClient(name = “SERVICE-A”)注意括號中的name要和ymp配置中的服務命名對應,二是@RequestMapping這個註解我喜歡在類上註解一個,方法上也註解一個,這樣可以方便的控制url的頭部內容,但是feign有一個bug,無法做到,雖然這個bug之後修復了,但是老版本的feign不能再類上註解@RequestMapping,問題解決可以參考我上面發的鏈接
具體使用方法:
1.直接用serviceimpl+@Controller註解,即可調用對應的web接口返回結果
2.其他微服務,調用@Resource註解注入Service然後調用方法即可

結束

這樣我們的基本的接口調用和MCV分層架構中的controller層就算是ok了。
github地址:https://github.com/alex9567/SpringCloudScaffold

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章