SpringBoot3x的服务间调用@HttpExchange

导读:本篇文章讲解 SpringBoot3x的服务间调用@HttpExchange,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

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

创建个SpringBoot3x项目

SpringBoot3x的服务间调用@HttpExchange

设置端口号为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项目,依赖如下

SpringBoot3x的服务间调用@HttpExchange

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

SpringBoot3x的服务间调用@HttpExchange

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的服务,返回结果如下:

SpringBoot3x的服务间调用@HttpExchange
SpringBoot3x的服务间调用@HttpExchange
SpringBoot3x的服务间调用@HttpExchange

这样就调用成功了。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/101708.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!