微服务间消息传递

微服务是一种软件开发架构,它将一个大型应用程序拆分为一系列小型、独立的服务。每个服务都可以
独立开发、部署和扩展,并通过轻量级的通信机制进行交互。

应用开发

common模块中包含服务提供者和服务消费者共享的内容
provider模块是服务的提供者,用于通过SpringMVC的控制器提供访问接口

服务提供者

控制层

@RestController
@RequestMapping("/users")
public class HelloController {
 @GetMapping("/hello")
 public String sayHello(@RequestParam String username) {
   if (username == null || username.trim().length() < 1)
     username = "MicroService";
   return "Provider: hello " + username + "!";
 }
}

服务消费者

服务消费者通过http协议访问服务提供者,可以使用JDK的URL或者使用HttpClient之类的工具,但是直
接使用工具比较繁琐,所以使用SpringBoot提供的RestTemplate进行访问
在主类或者当前应用的配置类上声明RestTemplate

@SpringBootApplication
public class ConsumerApplication {
  public static void main(String[] args) {
    SpringApplication.run(ConsumerApplication.class, args);
 }
  @Bean
  public RestTemplate restTemplate() {
    return new RestTemplate();
 }
}

核心配置,主要修改一下访问端口号,因为应用的默认端口都是8080,会有端口号冲突的问题

server.port=7081 

定义控制器实现访问服务提供者

@RestController
@RequestMapping("/consumer")
public class ConsumerController {
  @Autowired
  private RestTemplate restTemplate;
  @GetMapping("/{name}")
  public String test(@PathVariable String name){
    //RestTemplate针对RESTful中的get/post/delete/put分别提供了对应的方法
    String res =
restTemplate.getForObject("http://localhost:7080/users/hello?username=" +
name, String.class);
    return res;
 }
}

测试验证

在这里插入图片描述

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐