spring boot3.0新特性Http客户端远程调用

1、安装依赖


        
            org.springframework.boot
            spring-boot-starter-webflux
        

2、项目结构
spring boot3.0新特性Http客户端远程调用_第1张图片
3、新建配置类WebConfig

package com.example.springboot3.config;

import com.example.springboot3.client.UserClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;

@Configuration
public class WebConfig {
//    @Bean
//    WebClient webClient(ObjectMapper objectMapper) {
//        return WebClient.builder()
//                .baseUrl("http://localhost:8001")
//                .build();
//    }

    @Bean
    WebClient webClient() {
        return WebClient.builder()
                .baseUrl("http://localhost:8001")
                .build();
    }

    @SneakyThrows
    @Bean
    UserClient postClient(WebClient webClient) {
        HttpServiceProxyFactory httpServiceProxyFactory =
                HttpServiceProxyFactory.builder(WebClientAdapter.forClient(webClient))
                        .build();
        return httpServiceProxyFactory.createClient(UserClient.class);
    }
}

4、新建Http客户接口UserClient

package com.example.springboot3.client;

import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;

@HttpExchange(accept = "application/json", contentType = "application/json")
public interface UserClient {
    @GetExchange("/dubboTest")
    String getAllTest();
}

5、controller测试接口

package com.example.springboot3.controller;

import com.example.springboot3.client.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    UserClient userClient;

    @GetMapping("/test")
    public String test(){
        return userClient.getAllTest();
    }
}

6、调用的方式
@HttpExchange:是指定HTTP端点的通用注释。当在接口级别使用时,它适用于所有方法。
@GetExchange:为HTTP GET请求指定@HttpExchange。
@PostExchange:对于HTTP POST请求,指定@HttpExchange。
@PutExchange:为HTTP PUT请求指定@HttpExchange。
@DeleteExchange:对于HTTP DELETE请求,指定@HttpExchange。
@PatchExchange:对于HTTP Patch请求,指定@HttpExchange。
7、传递参数格式
@PathVariable:将请求URL中的值替换为占位符。
@RequestBody:提供请求的主体。
@RequestParam:添加请求参数。当“content-type”设置为“application/x-www-form-urlencoded”时,请求参数会在请求体中编码。否则,它们将作为URL查询参数添加。
@ requesttheader:添加请求头的名称和值。
@RequestPart:可用于添加请求部分(表单字段,资源或HttpEntity等)。
@CookieValue:向请求中添加cookie。

你可能感兴趣的:(spring,boot,http,spring)