Feign

Ribbon:从Eureka获取服务列表进行负载均衡,客户端负载均衡

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-ribbon</artifactId></dependency>
<dependency><groupId>com.quareup.okhttp3</groupId><artifactId>okhttp</artifactId></dependency>
@SpringBootApplication
@EnableDiscoveryClient
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class,args);
}

@Bean
@LoadBalanced//会走loadBalancerInterceptor拦截器
public RestTemplate restTemplate(){
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
}
SpringApplication.yml中添加
ribbon:
  MaxAutoRetries: 2 #最大重试次数,当Eureka中可以找到服务,但是服务连不上时会重试。
  MaxAutoRetriesNextServer: 3 #切换实例重试次数
  OkToRetryOnAllOptions: false #对所有操作请求都进行重试,如果是get则可以,如果是post、put等操作没有实现幂等情况很危险,所以设置false
  ConnectTimeout: 5000 #请求链接的超时时间
  ReadTimeout: 6000 #请求处理的超时时间
public void testRibbon(){
String serviceId = "其他微服务ID";
ResponseEntity<Map> forEntity = restTemplate.getForEntity("其他微服务url",Map.class);
Map body = forEntity.getBody();
}

Feign 是一个客户端负载均衡。Feign = Ribbon+okhttp

不需要ribbonjar包,feign自带
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>

<dependency><groupId>com.netflix.feign</groupId><artifactId>feign-okhttp</artifactId></dependency>

在应用主类中通过@EnableFeignClients注解开启Feign功能

启动文件FeignApplication.java
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignApplication.class, args);
    }
}

定义服务接口类UserClient.java,使用@FeignClient("XXX")注解来绑定该接口对应XXX服务
@FeignClient("XXX")
public interface UserClient {
    @RequestMapping(method = RequestMethod.GET, value = "/访问路径名称/{id}")
    public User getuserinfo(@PathVariale("id") Long id);//参数不为基本类型,是对象的时候只能使用post方法;
     
    @RequestLine("POST /")
  @Headers("Content-Type: application/json") // 这里JSON格式需要的花括号居然需要转码,""需要转码。
  @Body("%7B\"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D")
  public void json(@Param("user_name") String userName, @Param("password") String password);
     
    // 在使用 @Param 注解给模板中的参数设值的时候,默认的是使用的对象的 toString() 方法的值,通过声明 自定义的Param.Expander可以控制其行为,比如说格式化 Date 类型的值:
  @RequestLine("GET /?since={date}")
  public Result list(@Param(value = "date", expander = DateToMillis.class) Date date);
 
  //动态查询参数支持,通过使用 @QueryMap 可以允许动态传入请求参数
    @RequestLine("GET /find")    
    public find(@QueryMap Map<String, Object> queryMap);
}
在web层中调用上面定义的UserController,具体如下
@RestController
public class UserController {
 
    @Autowired
    UserClient userClient;
 
    @RequestMapping(value = "/getuserinfo", method = RequestMethod.GET)
    public User getuserinfo() {
        return userClient.getuserinfo();
    }
     
    @RequestMapping(value = "/json", method = RequestMethod.POST)
    public String json() {
        return userClient.json("denominator", "secret");
    }
     
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return userClient.list(new Date());
    }
  /**不使用@Autowired配置feign方式
  *GitHub github = Feign.builder()
  *  .encoder(new JacksonEncoder())//编码方式
  *  .decoder(new JacksonDecoder()) //解码方式
  *  .logger(new Logger.JavaLogger().appendToFile("logs/http.log")).logLevel(Logger.Level.FULL)//日志
  *  .requestInterceptor(new BasicAuthRequestInterceptor(username, password))//请求拦截器
  *  .target(GitHub.class, "https://api.github.com");//服务提供方类,链接
  */
}
 
总结:其实通过Feign封装了HTTP调用服务方法,使得客户端像调用本地方法那样直接调用方法,类似Dubbo中暴露远程服务的方式,区别在于Dubbo是基于私有二进制协议,而Feign本质上还是个HTTP客户端

posted @ 2018-04-28 17:06  袋子里的袋鼠  阅读(248)  评论(0编辑  收藏  举报