Spring Cloud Alibaba 使用Feign進行服務消費

SimpleWu發表於2021-11-05

為什麼使用Feign?

Feign可以把Rest的請求進行隱藏,偽裝成類似SpringMVC的Controller一樣。你不用再自己拼接url,拼接引數等等操作,一切都交給Feign去做。

使用Feign進行消費

將需要使用feign的工程增加一下依賴

pom.xml

<!-- openfeign 服務發現呼叫 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

啟動類增加啟用feign註解EnableFeignClients

UserServiceApplication.java

/**
 * 使用者中心服務啟動類
 *
 * @author wentao.wu
 */
@EnableDiscoveryClient//服務註冊
@EnableFeignClients//服務發現
@SpringBootApplication
public class UserServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }
}

建立feign呼叫介面

/**
 * service-member服務遠端呼叫介面
 * @author wentao.wu
 */
@FeignClient(name = "service-member")
public interface MemberInfoControllerClient {
    /**
     * 通過使用者名稱稱獲取會員資訊
     * @param username
     * @return
     */
    @GetMapping("/member/info/getUserMember/{username}")
    public Response<Map<String, Object>> getUserMember(@PathVariable("username") String username);
}

建立請求進行feign消費

FeignConsumerController.java

import com.gitee.eample.user.service.feign.MemberInfoControllerClient;
import com.gtiee.example.common.exception.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Feign template consumer
 *
 * @author wentao.wu
 */
@RestController
@RequestMapping("/feign/consumer")
public class FeignConsumerController {
    @Autowired
    private MemberInfoControllerClient client;

    @GetMapping("/getUserInfo/{username}")
    public Response<Map<String, Object>> getUserInfo(@PathVariable("username") String username) {
        Response<Map<String, Object>> response = client.getUserMember(username);
        Map<String, Object> userinfo = new HashMap<>();
        userinfo.put("userage", "100");
        userinfo.put("email", "xxx@email.com");
        response.getResult().putAll(userinfo);
        response.setMsg("獲取使用者資訊成功!");
        return response;
    }
}

以上程式碼通過Feign生命消費者介面方法,Feign將自動生成代理方法進行遠端呼叫。訪問請求http://localhost:8080/feign/consumer/getUserInfo/zhangsan 進行消費返回結果為

{
    "code": "1",
    "msg": "獲取使用者資訊成功!",
    "errorCode": null,
    "errorMsg": null,
    "result": {
        "level": "vip1",
        "username": "zhangsan",
        "userage": "100",
        "email": "xxx@email.com"
    }
}

原始碼程式碼存放地址

gitee: https://gitee.com/SimpleWu/spring-cloud-alibaba-example.git
cnblogs: https://www.cnblogs.com/SimpleWu
持續更新目錄:https://www.cnblogs.com/SimpleWu/p/15476427.html

相關文章