springboot reactive反应性微服务

Springboot反应性微服务

Spring公文包提供了两个并行堆栈。一种是基于带有Spring MVC和Spring数据结构的Servlet API。

另一个是利用Spring WebFlux和Spring Data的反应式存储库的完全反应式堆栈。在这两种情况下,Spring Security都为这两个堆栈提供了本机支持。

2.从简单的入手

构建反应式RESTful Web服务

例子中都返回英文的提示,修改为中文后,都是乱码,需要稍微修改一下代码

3.源代码

3.1定义一个Application,这个是项目的入口,并且目录GreetWebClient访问启动的地址,启动默认为localhost:8080

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

   public static void main(String[] args) {
      SpringApplication.run(Application.class, args);

      GreetingWebClient gwc = new GreetingWebClient();
      System.out.println(gwc.getResult());
   }
}

3.2 代码结构为

3.3 修改代码点为:红色部分,说明需要json字符集为UTF8

package hello;
...

@Component
public class GreetingHandler {

   public Mono<ServerResponse> hello(ServerRequest request) {


      return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
         .body(BodyInserters.fromValue("Hello, keny风清扬!"));
   }
}

3.4定义GreetingWebClient.java 红色部分修改点

package hello;

import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;

import reactor.core.publisher.Mono;

public class GreetingWebClient {
   private WebClient client = WebClient.create("http://localhost:8080");

   private Mono<ClientResponse> result = client.get()
         .uri("/hello")
         .accept(MediaType.APPLICATION_JSON_UTF8)
         .exchange();

   public String getResult() {
      return ">> result = " + result.flatMap(res -> res.bodyToMono(String.class)).block();
   }
}

4.运行效果

扫描二维码关注公众号,回复: 10601527 查看本文章
发布了301 篇原创文章 · 获赞 16 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/keny88888/article/details/105286857
今日推荐