Spring-Cloud 学习笔记-(6)Feign

Spring-Cloud 学习笔记-(6)Feign


在之前我们使用Ribbon来大大简化了远程调用的代码

String jsonStr = restTemplate.getForObject("http://user-service/api/v1/user/2", String.class);

如果就学到这里,你可能以后需要编写类似的大量重复代码,格式基本相同,无非参数不一样。有没有更优雅的方式,来对这些代码再次优化呢?

这就是我们接下来要学的Feign的功能了。

1、简介

有道词典的英文解释:

为什么叫伪装?

Feign可以把Rest的请求进行隐藏,伪装成类似SpringMVC的Controller一样。你不用再自己拼接url,拼接参数等等操作,一切都交给Feign去做。

项目主页:https://github.com/OpenFeign/feign

2、快速入门

2.1、加依赖

<!-- feign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2.2、启动类

//OrderApplication类

//把之前的RestTemplate去掉
@SpringBootApplication
@EnableCircuitBreaker//开启服务的熔断
@EnableFeignClients//开启Feign
public class OrderApplication {

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

2.3、编写UserClient接口

1545489437752

package com.bigfly.client;

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

/**
 * 用户服务接口
 */
@FeignClient("user-service")//标记这是一个fegin的远程调用客户端
public interface UserClient {

    //请求路径
    @RequestMapping("api/v1/user/{user_id}")
    String findUserById(@PathVariable("user_id")int id);
}

2.4、修改调用方法


//OrderServcieImpl类

    @Autowired
    private UserClient userClient;
....
    @Override
    public Order findById(int userId) {
		//我们把远程调用通过fegin伪装起来,内部fegin同样帮我们实现了负载均衡
        String jsonStr = userClient.findUserById(userId);

        JsonNode jsonNode = JsonUtils.str2JsonNode(jsonStr);
        Order order = new Order();
        order.setOrderName("我是一个订单");
        order.setSerialId(UUID.randomUUID().toString());
        order.setUserName(jsonNode.get("data").get("name").textValue());
        order.setPort(jsonNode.get("data").get("port").textValue());
        return order;
    }

2.5、测试

1545489700166

3、负载均衡

feign底层以及集成了ribbon的依赖了

也就是说,我们引入的Feign依赖过后,就不需要引入Ribbon的依赖了。application.yml配置依旧可以按照ribbon的方式配置负载均衡策略等信息。

4、Hystrix支持

4.1、开启Feign对Hystrix的支持

#开启feign对hystrix的支持
feign:
  hystrix:
    enabled: true

4.2、编写UserClient的实现类

package com.bigfly.fallback;

import com.bigfly.client.UserClient;
import org.springframework.stereotype.Component;
/**
*	作为UserClient调用失败后的执行类
*/
@Component
public class UserServiceFallBack implements UserClient {
	
    @Override
    public String findUserById(int id) {
        return "{\"data\":{\"name\":\"暂无此人\",\"port\":\"0000\"}}";
    }
}

4.3、标记失败执行类

//UserClient类

@FeignClient(value = "user-service",fallback = UserServiceFallBack.class)//标记这是一个fegin的远程调用客户端
public interface UserClient {

    //请求路径
    @RequestMapping("api/v1/user/{user_id}")
    String findUserById(@PathVariable("user_id")int id);
}

4.4、测试

关闭user-service 访问http://localhost:8781/api/v1/order/1

posted @ 2018-12-26 15:27  神秘的大飞子  阅读(232)  评论(0编辑  收藏  举报