Spring Cloud简介和服务中心的搭建

470 阅读1分钟

微服务

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();
        }
    }
}


搭建服务注册中心

  1. 新建一个maven 项目,删掉src目录

  1. 在maven 内添加 Spring Boot 节点

springcloud 版本要求严格

@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

搭建集群

  1. 拷贝两份配置文件

  1. 在 hosts 文件中添加配置
127.0.0.1 peer1
127.0.0.1 peer2
  1. 配置文件
# 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
  1. 打包 eureka

  2. 启动两个实例

java -jar eureka-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer1
java -jar eureka-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer2
  1. 启动成功