在引入Spring Cloud之前我们来看看各个服务之间是如何进行通信的,我们在spring中是以HTTP进行通信的,而spring boot又是基于spring的,所以在spring boot项目中也仍然是以http进行通信的
下面创建两个spring boot项目
创建项目
引入web依赖即可
第一个spring boot项目,取名httpserver,定义一个controller
package com.zhouym.httpserver;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 〈〉
*
* @author zhouym
* @create 2019/8/31
* @since 1.0.0
*/
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello,spring cloud";
}
}
另外一个spring boot项目,起名httpclient,直接在测试类中进行测试
package com.zhouym.httpclient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
@RunWith(SpringRunner.class)
@SpringBootTest
public class HttpclientApplicationTests {
@Test
public void contextLoads() throws IOException {
HttpURLConnection conn = null; //创建HttpURLConnection连接对象
URL url = new URL("http://localhost:8080/hello"); //创建URL对象,指定访问的接口,就是在httpserver中的controller接口
conn = (HttpURLConnection)url.openConnection();//创建连接对象
if (conn.getResponseCode() == 200){ //如果返回的响应码为200,则表示请求被httpserver接收成功
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); //由于httpserver返回的是一个字符串,这里用高效字符流进行接收
String s = reader.readLine();//读取流中的数据
System.out.println(s);
reader.close();//关闭资源连接
}
}
}
运行httpclient启动类,看看控制台的输出