首先,我们之前曾经用过很多服务间调用的方式和方法,今天给大家介绍一款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的服务,返回结果如下:
这样就调用成功了。