SpringBoot3x的服务间调用@HttpExchange

        首先,我们之前曾经用过很多服务间调用的方式和方法,今天给大家介绍一款SpringBoot3x版本服务间调用,采用@HttpExchange注解实现,方便快捷,简单易懂。

        创建个SpringBoot3x项目

        设置端口号为8081

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author xiarg
 * @CreateTime 2023/02/01  11:10
 */
@RestController
public class TestController {

    @GetMapping("/server/test")
    public String test(String name) {
        System.out.println(name);
        return "test :  " + name;
    }

}

         另外在创建个SpringBoot3x项目,依赖如下

         端口默认8080,代码结构如下:

         WebConfig如下,可以看到我们创建了一个web客户端,ToDoService代理客户端发送http请求

import com.genius.springboot3web.service.ToDoService;
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;

/**
 * @Author xiarg
 * @CreateTime 2023/02/01  14:06
 */
@Configuration
public class WebConfig {

    @Bean
    WebClient webClient() {
        return WebClient.builder()
                .baseUrl("http://localhost:8081")
                .build();
    }
    @Bean
    ToDoService toDoService() {
        HttpServiceProxyFactory httpServiceProxyFactory =
                HttpServiceProxyFactory.builder(WebClientAdapter.forClient(webClient()))
                        .build();
        return httpServiceProxyFactory.createClient(ToDoService.class);
    }

}

        ToDoService接口

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

/**
 *
 * 服务间调用
 * @Author xiarg
 * @CreateTime 2023/02/01  14:10
 */
@HttpExchange("/server")
public interface ToDoService {
    /**
     * 测试
     * @param name
     * @return
     */
    @GetExchange("/test")
    String test(@RequestParam String name);

}

        测试Controller

/**
 * @Author xiarg
 * @CreateTime 2023/02/01  11:10
 */
@RestController
public class TestController {

    @Autowired
    private ToDoService toDoService;

    @GetMapping("/test")
    public String test(){
        String test = toDoService.test("test1");
        System.out.println(test);
        return "name : "+test;
    }

}

        此时启动两个服务,调用http://localhost:8080/test接口,此时,8080的服务就会去调用8081的服务,返回结果如下:

         这样就调用成功了。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值