(谷粒项目十一)spring cloud Feign 基本应用demo

本项目中guli-microservice-statistics是FeignClients客户端

一、Feign基本概念

  • Feign是Netflix开发的声明式、模板化的HTTP客户端, Feign可以帮助我们更快捷、优雅地调用HTTP API。
  • Feign支持多种注解,例如Feign自带的注解或者JAX-RS注解等。
  • Spring Cloud对Feign进行了增强,使Feign支持了Spring MVC注解,并整合了Ribbon和Eureka,从而让Feign的使用更加方便。
  • Spring Cloud Feign是基于Netflix feign实现,整合了Spring Cloud Ribbon和Spring Cloud Hystrix,除了提供这两者的强大功能外,还提供了一种声明式的Web服务客户端定义的方式。
  • Spring Cloud Feign帮助我们定义和实现依赖服务接口的定义。在Spring Cloud feign的实现下,只需要创建一个接口并用注解方式配置它,即可完成服务提供方的接口绑定,简化了在使用Spring Cloud Ribbon时自行封装服务调用客户端的开发量。

二、实现服务调用

1、在调用端添加pom依赖

在statistics微服务中添加

<!--服务调用-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2、启动类添加注解

@EnableFeignClients

3、创建远程调用包和接口

创建client包和UcenterClient接口

@FeignClient注解用于指定从哪个服务中调用功能 ,名称与被调用的服务名保持一致。

@GetMapping注解用于对被调用的微服务进行地址映射。

@PathVariable注解一定要指定参数名称,否则出错

@Component注解防止,在其他位置注入UcenterClient时idea报错

package com.guli.statistics.client;
@Component
@FeignClient("guli-ucenter")
public interface UcenterClient {

    /**
     * 注意:一定要写成 @PathVariable("day"),圆括号中的"day"不能少
     * @param day
     * @return
     */
    @GetMapping(value = "/admin/ucenter/member/count-register/{day}")
    public R registerCount(@PathVariable("day") String day);
}

4、调用微服务

在调用端的DailyService中调用client中的方法

**接口

 void createStatisticsByDay(String day);

**实现

 @Autowired
private UcenterClient ucenterClient;

@Override
public void createStatisticsByDay(String day) {


    //删除已存在的统计对象
    QueryWrapper<Daily> dayQueryWrapper = new QueryWrapper<>();
    dayQueryWrapper.eq("date_calculated", day);
    baseMapper.delete(dayQueryWrapper);


    //获取统计信息
    Integer registerNum = (Integer) ucenterClient.registerCount(day).getData().get("countRegister");
    Integer loginNum = RandomUtils.nextInt(100, 200);//TODO
    Integer videoViewNum = RandomUtils.nextInt(100, 200);//TODO
    Integer courseNum = RandomUtils.nextInt(100, 200);//TODO

    //创建统计对象
    Daily daily = new Daily();
    daily.setRegisterNum(registerNum);
    daily.setLoginNum(loginNum);
    daily.setVideoViewNum(videoViewNum);
    daily.setCourseNum(courseNum);
    daily.setDateCalculated(day);

    baseMapper.insert(daily);
}

5、controller

package com.guli.statistics.controller.admin;

@CrossOrigin
@RestController
@RequestMapping("/admin/statistics/daily")
public class DailyAdminController {

    @Autowired
    private DailyService dailyService;

    @GetMapping("{day}")
    public R createStatisticsByDate(@PathVariable String day) {
        dailyService.createStatisticsByDay(day);
        return R.ok();
    }
}

6、Swagger测试

启动eureka、ucenter、statistics三个微服务

在swagger中测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,这里有一个简单的Spring Cloud Feign集成Protobuf的示例: 1. 首先,您需要在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>2.2.5.RELEASE</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-netty-shaded</artifactId> <version>1.37.0</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-protobuf</artifactId> <version>1.37.0</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-stub</artifactId> <version>1.37.0</version> </dependency> ``` 2. 创建Protobuf定义文件 在src/main/proto目录下创建一个名为`hello.proto`的文件,并添加以下内容: ```protobuf syntax = "proto3"; package io.github.xyz.spring.cloud.feign.protobuf.example.api; message HelloRequest { string name = 1; } message HelloResponse { string message = 1; } service HelloService { rpc hello(HelloRequest) returns (HelloResponse); } ``` 3. 生成Java代码 在pom.xml文件中添加以下插件,用于生成Java代码: ```xml <build> <plugins> <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.5.1</version> <configuration> <protocArtifact>com.google.protobuf:protoc:3.12.4:exe:${os.detected.classifier}</protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.37.0:exe:${os.detected.classifier}</pluginArtifact> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-custom</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ``` 然后运行`mvn protobuf:compile`和`mvn protobuf:compile-custom`,将生成的Java代码放在`target/generated-sources/protobuf`目录下。 4. 创建Feign客户端 创建一个Feign客户端,用于调用HelloService服务。在使用Protobuf时,需要使用`@RequestLine`注解,以指定使用哪个HTTP方法,并使用`@Headers`注解,以指定使用哪种消息类型。 ```java @FeignClient(name = "hello-service", configuration = HelloClientConfiguration.class) public interface HelloClient { @RequestLine("POST /hello") @Headers({"Content-Type: application/x-protobuf", "Accept: application/x-protobuf"}) HelloResponse hello(HelloRequest request); } ``` 5. 创建Feign配置 创建一个Feign配置类,用于配置Feign客户端。在使用Protobuf时,需要将`Encoder`和`Decoder`设置为`ProtobufEncoder`和`ProtobufDecoder`,并将`Content-Type`和`Accept`设置为`application/x-protobuf`。 ```java @Configuration public class HelloClientConfiguration { @Bean public Encoder protobufEncoder() { return new ProtobufEncoder(); } @Bean public Decoder protobufDecoder() { return new ProtobufDecoder(); } @Bean public Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } @Bean public Request.Options options() { return new Request.Options(5000, 10000); } } ``` 6. 创建服务端 创建一个服务端,用于提供HelloService服务。在使用Protobuf时,需要使用`@RequestBody`和`@ResponseBody`注解,以指定使用哪种消息类型。 ```java @RestController public class HelloController { @PostMapping("/hello") public HelloResponse hello(@RequestBody HelloRequest request) { return HelloResponse.newBuilder() .setMessage("Hello, " + request.getName() + "!") .build(); } } ``` 7. 配置Swagger 使用Swagger来测试Feign客户端。在Spring Boot应用中,可以使用Springfox Swagger来配置Swagger。 ```java @Configuration @EnableSwagger2 public class SwaggerConfiguration { @Bean public Docket docket() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } ``` 8. 启动应用 现在,您可以启动应用并访问http://localhost:8080/swagger-ui.html来测试Feign客户端了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

knight郭志斌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值