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

為什麼使用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", "[email protected]");
        response.getResult().putAll(userinfo);
        response.setMsg("獲取用戶資訊成功!");
        return response;
    }
}

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

{
    "code": "1",
    "msg": "獲取用戶資訊成功!",
    "errorCode": null,
    "errorMsg": null,
    "result": {
        "level": "vip1",
        "username": "zhangsan",
        "userage": "100",
        "email": "[email protected]"
    }
}

源碼程式碼存放地址

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