微服務
SOA 和 微服務
- SOA 服務治理中介軟體
- 解決叢集化部署,模組故障蔓延,模組呼叫出錯,模組呼叫負載均衡
- Spring Cloud 底層 http 呼叫
不使用框架進行跨服務訪問
- server1 中 介面
@RestController
public class HelloController {
@GetMapping("/hello")
public String test1(){
return "hello";
}
}
複製程式碼
- server2 中 訪問 server1中的服務
@RestController
public class HelloController {
@GetMapping("/test1")
public void test1() throws IOException {
URL url = new URL("http://localhost:8080/hello");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.connect();
if(con.getResponseCode() == 200){
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s = br.readLine();
System.out.println(s);
br.close();
}
}
@GetMapping("/test2")
public void test2() throws IOException {
URL url = new URL("http://localhost:8080/1.jpg");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.connect();
if(con.getResponseCode() == 200){
FileOutputStream fos = new FileOutputStream(new File("D:\\1.jpg"));
InputStream is = con.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1){
fos.write(buf,0,len);
}
fos.close();
is.close();
}
}
}
複製程式碼
搭建服務註冊中心
- 新建一個maven 專案,刪掉src目錄
![Spring Cloud簡介和服務中心的搭建](https://i.iter01.com/images/9e505dc583f8759c968852494a51c3c75ac6d20a319e0e4c8f6d184983bd0d6e.png)
- 在maven 內新增 Spring Boot 節點
![Spring Cloud簡介和服務中心的搭建](https://i.iter01.com/images/fbd60fa6f8318693b8dc2cbb1f71f0ec51dba1e37e673ddcc588288b886bf4f0.png)
springcloud 版本要求嚴格
![Spring Cloud簡介和服務中心的搭建](https://i.iter01.com/images/aa727629f165f133710f90828bd3d12c301d635354e01c925458a577444e0841.png)
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
複製程式碼
- 在 application.properties 中,既是微服務又是服務註冊中心 需要指定服務註冊中心的地址
server.port=1111
spring.application.name=eureka
eureka.client.register-with-eureka=true
# 指定服務註冊中心的地址
eureka.client.service-url.defaultZone=http://localhost:1111/eureka
複製程式碼
搭建叢集
- 拷貝兩份配置檔案
![Spring Cloud簡介和服務中心的搭建](https://i.iter01.com/images/735e734a0318bdd19616416ba25144206c7a2eafd769fe7872895f189f5c1c71.png)
- 在 hosts 檔案中新增配置
127.0.0.1 peer1
127.0.0.1 peer2
複製程式碼
- 配置檔案
# application-peer1.properties
server.port=1111
spring.application.name=eureka
eureka.instance.hostname=peer1
eureka.client.register-with-eureka=true
# 指定服務註冊中心的地址
eureka.client.service-url.defaultZone=http://peer2:1112/eureka
# application-peer2.properties
server.port=1112
spring.application.name=eureka
eureka.instance.hostname=peer2
eureka.client.register-with-eureka=true
# 指定服務註冊中心的地址
eureka.client.service-url.defaultZone=http://peer1:1111/eureka
複製程式碼
-
打包 eureka
-
啟動兩個例項
java -jar eureka-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer1
java -jar eureka-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer2
複製程式碼
- 啟動成功
![Spring Cloud簡介和服務中心的搭建](https://i.iter01.com/images/44c40f87dbe115f116fadaa9cf822a294d9d2659e4db76ef7d20e03b1ec6065e.png)