基于Eureka的远程调用 - Feign Client

在前面的文章中,我们构建了基于Eureka的RPC,但是获取地址,发起调用,对象转换都是手动完成。本文介绍Spring Cloud体系中专注完成RPC的Feign Client,大大简化PRC使用

本文是在Eureka快速体验基础上构建的,但是如果eureka已经连接好,可以不用关注

添加依赖


    org.springframework.cloud
    spring-cloud-starter-openfeign
    2.1.1.RELEASE

  • spring-cloud-starter-feign已经停止更新了,请使用spring-cloud-starter-openfeign

定义远程调用接口

  • 调用方HomeRemoteClient
//values是服务提供方在eureka注册的名字,path是该接口中所有请求url的前缀
@FeignClient(value = "tenmao-eureka-provider", path = "/home")
public interface HomeRemoteClient {
    //支持无参数调用
    @GetMapping("ping")
    String ping();

    //支持路径参数,URL参数, header以及body
    //支持对返回值自动进行HttpMessageConverter
    @PutMapping("/{personId}")
    WebResult updatePerson(@PathVariable("personId") int personId, @RequestParam("hobby") String hobby, @RequestHeader("Session-Id") String sessionId, @RequestBody Person person);
}
  • 对应的服务提供方HomeController
    在另外一个进程,该进程注册到eureka的名字是tenmao-eureka-provider,与服务调用方中value一致
@Slf4j
@RestController
@RequestMapping("home")
public class HomeController {
    @GetMapping("ping")
    public String ping() {
        return "success";
    }

    @PutMapping("/{personId:\\d+}")
    public WebResult update(@PathVariable int personId, @RequestParam String hobby, @RequestHeader("Session-Id") String sessionId, @RequestBody Person person) {
        if (person.getId() != personId) {
            return new WebResult<>(400, "id should be the same");
        }
        log.info("{}", person);
        log.info("sessionId: {}", sessionId);

        return new WebResult<>(hobby);
    }
}

使用

@EnableFeignClients
@SpringBootApplication
@EnableEurekaClient
public class EurekaClientApplication {
    @Resource
    private HomeRemoteClient homeRemoteClient;

    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication.class, args);
    }
    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {
            String result = homeRemoteClient.ping();
            System.out.println(result);

            Person tenmao = new Person(100, "tenmao", 20, true);
            WebResult webResult = homeRemoteClient.updatePerson(100, "basketball", UUID.randomUUID().toString(), tenmao);
            System.out.println(webResult);
        };
    }
}

一些高级配置

详细日志

  • 配置类
@Configuration
public class FeignConfiguration {
    @Bean
    Logger.Level feignLoggerLevel() {
        //这里记录所有,根据实际情况选择合适的日志level
        return Logger.Level.FULL;
    }
}

- 使用上述配置类
```java
@FeignClient(value = "tenmao-eureka-provider", configuration = FeignConfiguration.class, path = "/home")
public interface HomeRemoteClient {
    @GetMapping("ping")
    String ping();

    @PutMapping("/{personId}")
    WebResult updatePerson(@PathVariable("personId") int personId, @RequestParam("hobby") String hobby, @RequestHeader("Session-Id") String sessionId, @RequestBody Person person);
}
  • 启动配置(application.properties)
logging.level.com.tenmao.eurekaclient.remote=debug
  • 日志内容
[HomeRemoteClient#updatePerson] ---> PUT http://tenmao-eureka-provider/home/100?hobby=basketball HTTP/1.1
[HomeRemoteClient#updatePerson] Session-Id: 34155859-1b70-4104-b17a-b41d4b0010f2
[HomeRemoteClient#updatePerson] Content-Type: application/json;charset=UTF-8
[HomeRemoteClient#updatePerson] Content-Length: 87
[HomeRemoteClient#updatePerson] 
[HomeRemoteClient#updatePerson] {"id":100,"name":"tenmao","age":20,"gender":true,"birthTime":"2019-04-18T18:04:35.915"}
[HomeRemoteClient#updatePerson] ---> END HTTP (87-byte body)
[HomeRemoteClient#updatePerson] <--- HTTP/1.1 200 (11ms)
[HomeRemoteClient#updatePerson] content-type: application/json;charset=UTF-8
[HomeRemoteClient#updatePerson] date: Thu, 18 Apr 2019 10:07:36 GMT
[HomeRemoteClient#updatePerson] transfer-encoding: chunked
[HomeRemoteClient#updatePerson] 
[HomeRemoteClient#updatePerson] {"code":200,"msg":"success","data":"basketball"}
[HomeRemoteClient#updatePerson] <--- END HTTP (48-byte body)

日志显示了非常详细的HTTP协议内容

自定义HttpMessageConverter

@Slf4j
@Configuration
public class FeignConfiguration {
    
    private static final Gson GSON;
    static {
        final GsonBuilder gsonBuilder = new GsonBuilder();

        final DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        final DateTimeFormatter dateFmt = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        gsonBuilder.registerTypeAdapter(LocalDateTime.class, (JsonSerializer) (localDateTime, type, jsonSerializationContext) -> new JsonPrimitive(localDateTime.format(fmt)));
        gsonBuilder.registerTypeAdapter(LocalDateTime.class, (JsonDeserializer) (jsonElement, type, jsonDeserializationContext) -> {
            log.info("", jsonElement.getAsString());
            return LocalDateTime.parse(jsonElement.getAsString(), fmt);
        });

        gsonBuilder.registerTypeAdapter(LocalDate.class, (JsonSerializer) (localDate, type, jsonSerializationContext) -> new JsonPrimitive(localDate.format(dateFmt)));
        gsonBuilder.registerTypeAdapter(LocalDate.class, (JsonDeserializer) (jsonElement, type, jsonDeserializationContext) -> LocalDate.parse(jsonElement.getAsString(), dateFmt));

        gsonBuilder.serializeNulls();
        GSON = gsonBuilder.create();
    }
    
    @Bean
    public Encoder feignEncoder(){
        HttpMessageConverter jacksonConverter = new GsonHttpMessageConverter(GSON);
        ObjectFactory objectFactory = () -> new HttpMessageConverters(jacksonConverter);
        return new SpringEncoder(objectFactory);
    }

    @Bean
    public Decoder feignDecoder() {
        HttpMessageConverter jacksonConverter = new GsonHttpMessageConverter(GSON);
        ObjectFactory objectFactory = () -> new HttpMessageConverters(jacksonConverter);
        return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        //这里记录所有,根据实际情况选择合适的日志level
        return Logger.Level.FULL;
    }
}

参考

  • Eureka快速体验
  • Spring Cloud中如何优雅的使用Feign调用接口

你可能感兴趣的:(基于Eureka的远程调用 - Feign Client)