SpringCloud集成Openfeign

摘要:

OpenFeign与Ribbon都是负载均衡器,相比于Ribbon,OpenFrign集成了Ribbon、RestTemplate、Hystrix,同时也支持SpringMVC注解,它可以让我们像调方法一样简单地去调其他服务的接口,意味着Ribbon能做的事它都能做,且做的更好、更加简单强大

注意事项:

如果请求参数没有注解,那么默认为Post请求;服务名称不可含有下划线

一:引入依赖

<!--引入OpenFeign依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

二:在启动类上打上注解@EnableFeignClients开启OpenFeign支持

三:编写Feign接口,调用其他服务的接口【Feign底层通过动态代理使用RestTemplate自动发起调用实现】

package cn.ybl.FeignClient;

import cn.ybl.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
  * UserServer的feign客户端
  */
@FeignClient("UserServer") //调用的服务的应用名称
@RequestMapping("/user") //调用的服务的接口统一前缀
public interface UserFeignClient {

    /**
	  * 1.方法名称必须跟被代理服务接口方法名称一致
	  * 2.请求路径必须跟被代理服务接口一致
	  * 3.参数与返回值必须跟被代理服务接口一致
	  * 建议将要调用的服务的接口直接复制过来再删掉方法体
	  */
    @GetMapping("/{ids}")
    User getUser(@PathVariable("ids")Long id);
}

 四:Controller层注入Feign接口,去调用Feign接口的方法,就可以完成对其他服务的调用

package cn.ybl.Controller;

import cn.ybl.FeignClient.UserFeignClient;
import cn.ybl.pojo.User;
import com.netflix.discovery.converters.Auto;
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.RestController;

@RestController
public class PayServerController {

    //注入feign接口
    @Autowired
    private UserFeignClient userFeignClient;

    @GetMapping("/{id}")
    public User getById(@PathVariable("id") Long id){
        // 调用OpenFeign接口方法,访问UserServer服务
        return userFeignClient.getUser(id);
    }
}

因为它集成了Ribbon,所以我们不需要做任何配置就可以支持负载均衡

posted @ 2022-08-20 15:15  yyybl  阅读(59)  评论(0)    收藏  举报