SpringCloud第五章(服务调用负载均衡OpenFeign)

目录

1:什么是openfeign

2:openfeign的作用

3:openfeign案例使用,访问localhost:8072/test

3.1:pom配置,引入openfeign包

3.2:客户端定义相同的controller接口方法使用FeignClient注解

3.2:客户端controller的方法

3.3启动类使用@EnableFeignClients注解

4:openfeign调用超时

5:openfeign日志管理

5.1:自定义类

5.2:配置文件


1:什么是openfeign

封装了http协议,调用方式改成面向接口。在服务中我们有了eureka的服务发现和服务注册,那么怎么调用服务呢?在上一章中,我们会用了Robbin的http的restTemplate调用。但是程序员喜欢面向接口的编程,调用别人的controller方法要是能够像调用本地方法一样,那该多好呢。所以openfeign来了。

 

2:openfeign的作用

就是封装http,远程调用controller跟调用本地方法一样。

3:openfeign案例使用,访问localhost:8072/test

3.1:pom配置,引入openfeign包

<dependencies>
        <!--Spring web 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--引入openfeign jar-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--Springcloud的eureka组件  client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--图形监控-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

       

    </dependencies>

3.2:客户端定义相同的controller接口方法使用FeignClient注解

方法名字一样,使用FeignClient注解

//UserController接口的方法和服务端方法名字一样

@FeignClient(value = "client")  //value的名字是eureka中注册的名字
public interface UserControllerClient {

    @RequestMapping(value = "add",method = RequestMethod.GET)
    public String add();
}

3.2:客户端controller的方法

注入接口,跟调用本地方法似的

 @Autowired
   UserControllerClient userControllerClient;

    @RequestMapping("/test")
    public String hello1() {
        //调用远程controller跟调用本地方法似的,此处思想跟dubbo一致
        //真正的远程端口返回端口号
       String a= userControllerClient.add();
        return "111:"+a;
    }

3.3启动类使用@EnableFeignClients注解

@SpringBootApplication
@ComponentScan(basePackages= {"com.thit"})
@EnableFeignClients //启动类添加注解
public class Consumer2Application {
    public static void main(String[] args) {
        SpringApplication.run(Consumer2Application.class,args);
    }
}

 

4:openfeign调用超时

#建立连接时间
ribbon.ConnectTimeout=10000
#连接超时时间
ribbon.ReadTimeout=6000

5:openfeign日志管理

5.1:自定义类

@Configuration
public class FenConfig {
    @Bean
    Logger.Level fenlog(){
        //full
        return Logger.Level.FULL;

    }
}

5.2:配置文件

#logging.level.接口名字:debug
logging.level.com.thit.fencilent.UserControllerClient:debug

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值