这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos
前文《五分钟搞懂spring-cloud-square》详细介绍了什么是spring-cloud-square,以及三种实现类型的详细概念,爱动手的您已迫不及待想编码体验spring-cloud-square了,本篇咱们就来畅快实战,体验这个spring官方带给我们的smart client
如标题所述,接下里咱们会将spring-cloud-square提供的三种client都编码体验,总的来说本篇由以下内容构成:
名称 | 链接 | 备注 |
---|---|---|
项目主页 | https://github.com/zq2599/blog_demos | 该项目在GitHub上的主页 |
git仓库地址(https) | https://github.com/zq2599/blog_demos.git | 该项目源码的仓库地址,https协议 |
git仓库地址(ssh) | git@github.com:zq2599/blog_demos.git | 该项目源码的仓库地址,ssh协议 |
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.4</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.bolingcavalry</groupId> <artifactId>spring-cloud-square-tutorials</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <java.version>1.8</java.version> <spring-cloud.version>2020.0.2</spring-cloud.version> <square.dependency.version>0.4.0-SNAPSHOT</square.dependency.version> </properties> <packaging>pom</packaging> <description>Demo project for Spring Cloud Square Retrofit Web</description> <modules> <module>provider</module> <module>eureka</module> <module>consumer-okhttp</module> <module>client</module> <module>consumer-retrofit-okhttp</module> <module>consumer-retrofit-webflux</module> </modules> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.14.9</version> <scope>compile</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.7</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-square-okhttp</artifactId> <version>${square.dependency.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-square-retrofit</artifactId> <version>${square.dependency.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-boot-starter-webflux</artifactId> <version>${square.dependency.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-square-retrofit-webclient</artifactId> <version>${square.dependency.version}</version> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <!--skip deploy (this is just a test module) --> <artifactId>maven-deploy-plugin</artifactId> <configuration> <skip>true</skip> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> </pluginRepositories> </project>
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-cloud-square-tutorials</artifactId> <groupId>com.bolingcavalry</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>eureka</artifactId> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <start-class>com.bolingcavalry.eureka.EurekaApplication</start-class> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <!-- <version>Finchley.BUILD-SNAPSHOT</version>--> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <!-- defined in spring-cloud-starter-parent pom (as documentation hint), but needs to be repeated here --> <configuration> <requiresUnpack> <dependency> <groupId>com.netflix.eureka</groupId> <artifactId>eureka-core</artifactId> </dependency> <dependency> <groupId>com.netflix.eureka</groupId> <artifactId>eureka-client</artifactId> </dependency> </requiresUnpack> </configuration> </plugin> <plugin> <!--skip deploy (this is just a test module) --> <artifactId>maven-deploy-plugin</artifactId> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </build> </project>
server: port: 8761 spring: application: name: eureka eureka: client: registerWithEureka: false fetchRegistry: false server: waitTimeInMsWhenSyncEmpty: 0
package com.bolingcavalry.eureka; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurekaApplication { public static void main(String[] args) throws Exception { SpringApplication.run(EurekaApplication.class, args); } }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-cloud-square-tutorials</artifactId> <groupId>com.bolingcavalry</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>provider</artifactId> <packaging>jar</packaging> <dependencies> <dependency> <groupId>com.bolingcavalry</groupId> <artifactId>client</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-context</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <!-- 如果父工程不是springboot,就要用以下方式使用插件,才能生成正常的jar --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>com.bolingcavalry.provider.ProviderApplication</mainClass> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
spring: application: name: provider server: port: 18080 eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/
package com.bolingcavalry.provider; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } }
package com.bolingcavalry.provider.controller; import com.bolingcavalry.client.HelloResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Random; @RestController public class Hello { public static final String HELLO_PREFIX = "Hello World"; @Autowired DiscoveryClient client; /** * 随机取一个provider实例,返回其描述信息, * 如果只有一个provider实例时,返回的就是当前服务信息 * @return */ private String providerDescription() { List<ServiceInstance> instances = client.getInstances("provider"); ServiceInstance selectedInstance = instances .get(new Random().nextInt(instances.size())); return String.format("serviceId [%s], host [%s], port [%d]", selectedInstance.getServiceId(), selectedInstance.getHost(), selectedInstance.getPort()); } private String dateStr(){ return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()); } @GetMapping("/hello-str") public String helloStr() { List<ServiceInstance> instances = client.getInstances("provider"); ServiceInstance selectedInstance = instances .get(new Random().nextInt(instances.size())); return HELLO_PREFIX + " : " + providerDescription() + ", " + dateStr(); } @GetMapping("/hello-obj") public HelloResponse helloObj(@RequestParam("name") String name) { return new HelloResponse(name, dateStr(), providerDescription()); } }
接下来要创建的应用consumer-okhttp,使用的是spring-cloud-square三种能力的第一种:okhttp
pom.xml内容如下,重点是spring-cloud-square-okhttp和spring-cloud-starter-loadbalancer这两个库的引入:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-cloud-square-tutorials</artifactId> <groupId>com.bolingcavalry</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>consumer-okhttp</artifactId> <packaging>jar</packaging> <dependencies> <dependency> <groupId>com.bolingcavalry</groupId> <artifactId>client</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-square-okhttp</artifactId> <version>0.4.0-SNAPSHOT</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency> </dependencies> <build> <plugins> <!-- 如果父工程不是springboot,就要用以下方式使用插件,才能生成正常的jar --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>com.bolingcavalry.ConsumerApplication</mainClass> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
spring: application: name: consumer-okhttp server: port: 18081 eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/
package com.bolingcavalry.consumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OkhttpApplication { public static void main(String[] args) { SpringApplication.run(OkhttpApplication.class, args); } }
package com.bolingcavalry.consumer; import okhttp3.OkHttpClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration class OkHttpClientConfig{ @Bean @LoadBalanced public OkHttpClient.Builder okHttpClientBuilder() { return new OkHttpClient.Builder(); } }
package com.bolingcavalry.consumer.controller; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController public class RemoteHello { @Autowired private OkHttpClient.Builder builder; @GetMapping("/remote-str") public String hello() throws IOException { // 直接使用服务名 Request request = new Request.Builder().url("http://provider/hello-str").build(); // 远程访问 Response response = builder.build().newCall(request).execute(); return "get remote response : " + response.body().string(); } }
package com.bolingcavalry.consumer.controller; import com.bolingcavalry.client.Constants; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc @Slf4j class RemoteHelloTest { @Autowired private MockMvc mvc; @Test void hello() throws Exception { String responseString = mvc.perform(MockMvcRequestBuilders.get("/remote-str").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(containsString(Constants.HELLO_PREFIX))) .andDo(print()) .andReturn() .getResponse() .getContentAsString(); log.info("response in junit test :\n" + responseString); } }
接下来的两个应用都使用了当下热门的retrofit,再搭配Spring Cloud LoadBalance实现服务注册发现,当然了retrofit自身无法完成网络请求处理,要依赖其他库,先看okhttp库的
新建应用consumer-retrofit-okhttp,其pom.xml如下,要注意的必须依赖spring-cloud-square-retrofit和spring-cloud-square-okhttp,另外,为了:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-cloud-square-tutorials</artifactId> <groupId>com.bolingcavalry</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>consumer-retrofit-okhttp</artifactId> <dependencies> <dependency> <groupId>com.bolingcavalry</groupId> <artifactId>client</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-square-retrofit</artifactId> <version>0.4.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-square-okhttp</artifactId> <version>0.4.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <!--skip deploy (this is just a test module) --> <artifactId>maven-deploy-plugin</artifactId> <configuration> <skip>true</skip> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
spring: application: name: consumer-retrofit-okhttp server: port: 18082 eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/
package com.bolingcavalry.consumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RetrofitOkhttpApplication { public static void main(String[] args) { SpringApplication.run(RetrofitOkhttpApplication.class, args); } }
package com.bolingcavalry.consumer; import okhttp3.OkHttpClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.square.retrofit.EnableRetrofitClients; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableRetrofitClients class OkHttpClientConfig{ @Bean @LoadBalanced public OkHttpClient.Builder okHttpClientBuilder() { return new OkHttpClient.Builder(); } }
package com.bolingcavalry.consumer.service; import com.bolingcavalry.client.HelloResponse; import org.springframework.cloud.square.retrofit.core.RetrofitClient; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; @RetrofitClient("provider") public interface HelloService { @GET("/hello-obj") Call<HelloResponse> hello(@Query("name") String name); }
package com.bolingcavalry.consumer.controller; import com.bolingcavalry.client.HelloResponse; import com.bolingcavalry.consumer.service.HelloService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController public class RemoteHello { @Autowired(required = false) HelloService helloService; @GetMapping("/remote-obj") public HelloResponse hello(@RequestParam("name") String name) throws IOException { return helloService.hello(name).execute().body(); } }
看到这里,聪明的您一定会觉得欣宸就是个没见过世面的乡巴佬:定义HelloService 接口,无需开发实现类,这玩意在mybatis不就有了嘛,居然敢说"神奇",我觉得您说得对,欣宸确实没见识,大惊小怪的…
单元测试类如下,由于返回的是json对象,因此可以用andExpect方法再配合MockMvcResultMatchers,对json进行检查:
package com.bolingcavalry.consumer.controller; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc @Slf4j class RemoteHelloTest { private MockMvc mvc; @Autowired private WebApplicationContext webApplicationContext; @BeforeEach public void setUp() { // 在单元测试的时候,MockHttpServletResponse实例的characterEncoding默认是ISO-8859-1, // 得到的字符串打印出来也是乱码, // 下面的设置可以解决此问题 if (null==mvc) { mvc = MockMvcBuilders .webAppContextSetup(webApplicationContext) .addFilter((request, response, chain) -> { response.setCharacterEncoding("UTF-8"); // this is crucial chain.doFilter(request, response); }, "/*") .build(); } } @Test void hello() throws Exception { // 请求参数是用户名,实时生成一个 String name = System.currentTimeMillis() + "程序员A"; // 请求 String responseString = mvc.perform( MockMvcRequestBuilders .get("/remote-obj") .param("name", name) .accept(MediaType.APPLICATION_JSON) ) .andExpect(status().isOk()) // 验证状态 .andExpect(jsonPath("$.name", is(name))) // 验证json中返回的字段是否含有name .andDo(print()) .andReturn() .getResponse() .getContentAsString(); log.info("response in junit test :\n" + responseString); } }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-cloud-square-tutorials</artifactId> <groupId>com.bolingcavalry</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>consumer-retrofit-webflux</artifactId> <dependencies> <dependency> <groupId>com.bolingcavalry</groupId> <artifactId>client</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-square-retrofit</artifactId> <version>0.4.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-square-retrofit-webclient</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <!--skip deploy (this is just a test module) --> <artifactId>maven-deploy-plugin</artifactId> <configuration> <skip>true</skip> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
spring: application: name: consumer-retrofit-webflux server: port: 18083 eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/
package com.bolingcavalry.consumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RetrofitWebfluxApplication { public static void main(String[] args) { SpringApplication.run(RetrofitWebfluxApplication.class, args); } }
package com.bolingcavalry.consumer; import okhttp3.OkHttpClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.square.retrofit.webclient.EnableRetrofitClients; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.function.client.WebClient; @Configuration @EnableRetrofitClients class AppConfiguration { @Bean @LoadBalanced public WebClient.Builder builder() { return WebClient.builder(); } }
package com.bolingcavalry.consumer.service; import com.bolingcavalry.client.HelloResponse; import org.springframework.cloud.square.retrofit.core.RetrofitClient; import reactor.core.publisher.Mono; import retrofit2.http.GET; import retrofit2.http.Query; @RetrofitClient("provider") public interface HelloService { @GET("/hello-obj") Mono<HelloResponse> hello(@Query("name") String name); }
package com.bolingcavalry.consumer.controller; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc @Slf4j class RemoteHelloTest { private MockMvc mvc; @Autowired private WebApplicationContext webApplicationContext; @BeforeEach public void setUp() { // 在单元测试的时候,MockHttpServletResponse实例的characterEncoding默认是ISO-8859-1, // 得到的字符串打印出来也是乱码, // 下面的设置可以解决此问题 if (null==mvc) { mvc = MockMvcBuilders .webAppContextSetup(webApplicationContext) .addFilter((request, response, chain) -> { response.setCharacterEncoding("UTF-8"); // this is crucial chain.doFilter(request, response); }, "/*") .build(); } } @Test void hello() throws Exception { // 请求参数是用户名,实时生成一个 String name = System.currentTimeMillis() + "程序员B"; // 请求 String responseString = mvc.perform( MockMvcRequestBuilders .get("/remote-obj") .param("name", name) .accept(MediaType.APPLICATION_JSON) ) .andExpect(status().isOk()) // 验证状态 .andExpect(jsonPath("$.name", is(name))) // 验证json中返回的字段是否含有name .andDo(print()) .andReturn() .getResponse() .getContentAsString(); log.info("response in junit test :\n" + responseString); } }
我是欣宸,期待与您一同畅游Java世界…