1.加入webflux依赖,完整pom.xml如下:
4.0.0 cn.edu.tju springcloudloadbalancer1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent2.3.7.RELEASE org.springframework.cloud spring-cloud-dependenciesHoxton.SR12 pom import org.springframework.boot spring-boot-starter-weborg.slf4j slf4j-log4j12com.google.code.gson gson2.8.6 org.mybatis.spring.boot mybatis-spring-boot-starter1.3.2 org.springframework.cloud spring-cloud-starter-loadbalancermysql mysql-connector-java5.1.30 org.springframework.cloud spring-cloud-starter-netflix-eureka-client2.1.0.RELEASE org.springframework.boot spring-boot-starter-webflux2.3.7.RELEASE org.springframework.boot spring-boot-maven-plugin
2.创建配置类:
package cn.edu.tju.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.function.client.WebClient; @Configuration public class WebClientConfig { @Bean @LoadBalanced public WebClient.Builder loadBalancedWebClientBuilder() { return WebClient.builder(); } }
3.在controller中注入配置类,并调用其builder()方法产生WebClient对象,然后调用微服务并返回结果
package cn.edu.tju.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; @RestController public class ReactiveController { @Autowired private WebClient.Builder webClientBuilder; @RequestMapping("/react") public Monoreact(){ System.out.println("in react controller!"); WebClient webClient=webClientBuilder.build(); Mono stringMono = webClient.get().uri("http://demoservice/test").retrieve().bodyToMono(String.class); return stringMono; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)