前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringCloud实战:feign<下>

SpringCloud实战:feign<下>

作者头像
田维常
发布2019-07-16 10:58:30
4470
发布2019-07-16 10:58:30
举报

上篇简单的介绍了Feign的使用,本篇将结合注册中心,进行Feign的高级应用,案例中有三个角色:服务注册中心、服务提供者、服务消费者,注册中心为上篇的eureka单机版。

具体高级应用为如下几条:

1.使用feign进行服务间的调用

2.feign开启Gzip压缩

3.feign开启日志

4.feign替换JDK默认的URLConnection为okhttp

5.feign超时设置

6.feign使用hystrix进行熔断、降级处理

使用feign进行服务间的调用

服务提供者

创建provider-service服务提供者,添加如下依赖:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

application.properties配置文件代码如下:

server.port=9600
spring.application.name=provider-service
eureka.instance.prefer-ip-address=true
#配置注册中心地址
eureka.client.serviceUrl.defaultZone=http://zy:zy123@localhost:10025/eureka/

启动主类添加@EnableDiscoveryClient

@EnableDiscoveryClient
@SpringBootApplication
public class ProviderServiceApplication {
  public static void main(String[] args) {
    SpringApplication.run(ProviderServiceApplication.class, args);
  }
}

创建HelloController,添加一个hello方法

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(String name){
        return  "hello " + name;
    }
}

服务消费者

创建consumer-service服务提供者,添加如下依赖:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 因为要使用feign调用其他服务,所以需要添加此依赖 -->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

application.properties配置文件代码如下:

server.port=9700
spring.application.name=consumer-service
eureka.instance.prefer-ip-address=true
# 配置注册中心地址
eureka.client.serviceUrl.defaultZone=http://zy:zy123@localhost:10025/eureka/

启动主类添加@EnableDiscoveryClient、@EnableFeignClients2个注解

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerServiceApplication {
  public static void main(String[] args) {
    SpringApplication.run(ConsumerServiceApplication.class, args);
  }
}

创建一个接口HelloFeignService,调用服务提供者

//name为服务提供者向注册中心注册的实例名
@FeignClient(name = "provider-service" )
public interface HelloFeignService {
    //地址为服务提供者对外暴露的地址
    @RequestMapping(value = "/hello" , method = RequestMethod.GET)
    String hello(@RequestParam("name") String name);
}

创建IndexController控制器,注入feign,像本地方法一样调用服务提供者的服务

@RestController
public class IndexController {
    @Autowired 
    private HelloFeignService feignService;
    @RequestMapping(value = "/hello" , method = RequestMethod.GET)
    public String hello(String name){
        return feignService.hello(name);
    }
}

启动2个项目,访问服务消费者 http://localhost:9700/hello?name=zy ,效果如下说明feign调用成功

高级应用的第一点ok了。

feign开启Gzip压缩

Spring Cloud Feign支持对请求与响应的压缩,以提高通信效率,在服务消费者配置文件开启压缩支持和压缩文件的类型即可

#feign 请求与响应的压缩
feign.compression.request.enabled=true
feign.compression.response.enabled=true
feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=2048

feign开启日志

feign开启日志有两种方式,一种是使用配置文件,一种是使用java代码,下面将介绍代码方式

创建FeignLogConfig类,添加一个LoggerBean

@Configuration
public class FeignLogConfig {
    /**
     * 日志level有4个级别
     * 1.NONE,不记录任何日志
     * 2.BASIC,仅记录请求方法、URL以及响应状态码和执行时间
     * 3.HEADRES,除了BASIC以外的还会记录请求和响应的头信息
     * 4.FULL,所有
     * @return
     */
    @Bean
    Logger.Level feignLogger(){
        return Logger.Level.FULL;
    }
}

feign替换JDK默认的URLConnection为okhttp

使用okhttp,能提高qps,因为okhttp有连接池和超时时间进行调优

在服务消费者中,添加feign-okhttp依赖

<dependency>
  <groupId>io.github.openfeign</groupId>
  <artifactId>feign-okhttp</artifactId>
</dependency>

在配置文件中,禁用默认的http,启用okhttp

feign.httpclient.enabled=false
feign.okhttp.enabled=true

创建OkHttpConfig类,添加okhttp的bean

/**
 * 配置okhttp与连接池
 * ConnectionPool默认创建5个线程,保持5分钟长连接
 */
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class OkHttpConfig {
    @Bean
    public okhttp3.OkHttpClient okHttpClient(){
        return new okhttp3.OkHttpClient.Builder()
                //设置连接超时
                .connectTimeout(10 , TimeUnit.SECONDS)
                //设置读超时
                .readTimeout(10 , TimeUnit.SECONDS)
                //设置写超时
                .writeTimeout(10 , TimeUnit.SECONDS)
                //是否自动重连
                .retryOnConnectionFailure(true)
                .connectionPool(new ConnectionPool(10 , 5L, TimeUnit.MINUTES))
                .build();
    }
}

feign超时设置

# feign启用hystrix,才能熔断、降级
feign.hystrix.enabled=true

# hystrix的超时时间
hystrix.command.default.execution.timeout.enabled=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000

# ribbon的超时时间
ribbon.ReadTimeout=10000
ribbon.ConnectTimeout=10000

feign使用hystrix进行熔断、降级处理

上面的超时时间设置为10秒,把服务提供者sleep睡眠时间大于10秒,服务消费者就会触发hystrix,进行熔断保护

改造服务提供者,让服务睡眠60秒

@RequestMapping("/hello")
    public String hello(String name){
        try {
            //睡眠60秒,测试feign的熔断、降级
            Thread.sleep(60 * 1000);
        }catch (Exception e){
            e.printStackTrace();
        }
        return  "hello " + name;
    }

改造服务消费者,添加feign的熔断、降级方法,feign的hystrix熔断降级很好实现,只要在FeignClient的fallback回滚方法中指定那个实现类即可

@FeignClient(name = "provider-service" , fallback = HelloFeignFallbackService.class)
public interface HelloFeignService {
    @RequestMapping(value = "/hello" , method = RequestMethod.GET)
    String hello(@RequestParam("name") String name);
}

HelloFeignFallbackService代码如下:

/**
 * hystrix服务降级处理,防止因超时、异常等导致的服务调用雪崩
 */
@Service
public class HelloFeignFallbackService implements HelloFeignService{
    @Override
    public String hello(String name) {
        return "未找到" + name ;
    }
}

然后启动服务提供者与消费者,再访问 http://localhost:9700/hello?name=zy ,发现页面缓了10来秒,就直接返回了熔断方法中的内容,说明hystrix熔断降级成功

代码已上传至码云,源码,项目使用的版本信息如下:

  • SpringBoot 2.0.6.RELEASE
  • SpringCloud Finchley.SR2(非常新的版本)

源码地址: https://gitee.com/zhuyu1991/spring-cloud/ 原文地址: https://blog.csdn.net/zhuyu19911016520/article/details/84963568

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-06-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Java后端技术栈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档