springBoot使用webclient的demo

webclient采用非阻塞的方式实现http调用。RestTemplate采用的是阻塞式的方式。

为了更好的展示两者的区别,下面我们写了一个demo,供大家参考

先创建一个供调用的接口

package com.wc.www.ScBus.restcontroller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.wc.www.ScBus.entity.Tweet;

@RestController
@RequestMapping("/test")
public class TestController {
	
	@GetMapping("/slow-service-tweets")
	private List getAllTweets() {
	    try {
			Thread.sleep(2000L);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // delay
	    return Arrays.asList(
	      new Tweet("RestTemplate rules", "@user1"),
	      new Tweet("WebClient is better", "@user2"),
	      new Tweet("OK, both are useful", "@user1"));
	}
}

实体类Tweet:

package com.wc.www.ScBus.entity;

public class Tweet {

	private String desc;
	
	private String user;

	public Tweet() {
		
	}
	
	public Tweet(String desc, String user) {
		super();
		this.desc = desc;
		this.user = user;
	}



	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}
	
	
}

下面展示两种调用的demo

RestTemplate:

    @ResponseBody
    @GetMapping("/tweets-blocking")
    public List getTweetsBlocking() {
	    System.out.println("Starting BLOCKING Controller!");
	    final String uri = "http://127.0.0.1:8080/test/slow-service-tweets";
	    RestTemplate restTemplate = new RestTemplate();
		
		ResponseEntity> response = restTemplate.exchange( uri,
		  HttpMethod.GET, null, new ParameterizedTypeReference>(){});
		
	    List result = response.getBody();
	    System.out.println(result);
	    System.out.println("Exiting BLOCKING Controller!");
	    return result;
	}

调用接口:http://127.0.0.1:8080/page/tweets-blocking可以获得下面的结果

webClient:

    @ResponseBody
    @GetMapping(value = "/tweets-non-blocking", produces =     MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux getTweetsNonBlocking() {
		Tweet tw = new Tweet();
	    System.out.println("Starting NON-BLOCKING Controller!");
	    Flux tweetFlux = WebClient.create()
	      .get()
	      .uri("http://127.0.0.1:8080/test/slow-service-tweets")
	      .retrieve()
	      .bodyToFlux(Tweet.class);
	 
	    tweetFlux.subscribe(tweet -> System.out.println(tweet.toString()));
	    System.out.println("Exiting NON-BLOCKING Controller!");
	    return tweetFlux;
	}

调用接口:http://127.0.0.1:8080/page/tweets-non-blocking可以获得下面的结果

springBoot使用webclient的demo_第1张图片

通过两个结果的对比,就可以很清晰的看出区别了。webClient直接输出调用方法后面的代码,没有等待结果返回。而RestTemplate则是等待结果返回后才输出后面的代码

你可能感兴趣的:(spring,boot)