spring cloud入门demo
1.创建一个maven(空)工程,例如:springCloudLearning01
2.在maven工程中创建一个module工程,这是创建eureka-server,类似生产者
按图中选择创建
直接下一步,直到完成
3.在启动类增加注解 @EnableEurekaServer,表明这是一个server
package com.tencent.eurekaserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
/**
* 开启这个注解表明这是一个EurekaServer
*/
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
在application.yml中配置
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
#通过eureka.client.registerWithEureka:false和fetchRegistry:false来表明自己是一个eureka serve
registerWithEureka: false
fetchRegistry: false
serviceUrl:
#指明client需要设置defaultZone为这个地址
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
此时可以直接访问:http://localhost:8761/
可以看到如下的界面,此时是没有服务消费者的
4.再次创建一个module,这次是创建一个消费者,eureka-hi
创建的方法和创建server一样,也是选择 cloud-Discovery和Eureka Server
创建好了之后,在启动类增加注解 @EnableEurekaClient,表明这是一个服务消费者
package com.tencent.servicehi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
/**
* 表明这是一个eurekaClient
*/
@EnableEurekaClient
public class ServiceHiApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceHiApplication.class, args);
}
}
在application.yml中配置,需要注意点,已经在注释上面提示了
eureka:
client:
serviceUrl:
#连接server指明的defaultZone,两者必须一致,否则连接不上
defaultZone: http://localhost:8761/eureka/
server:
port: 8762
spring:
application:
#表示client的一个标识名称,不重复
name: service-hi
创建一个controller用来测试
package com.tencent.servicehi.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping("/hi")
public String home(@RequestParam String name) {
return "欢迎访问spring cloud eurekaClient";
}
}
启动项目,可以看到,此时多了一个服务消费者,名称为service-hi,端口号为8762
这个时候,就可以访问controller了,可以看到访问成功了,访问的地址:http://localhost:8762/hi?name=yu
此时一个简单的spring cloud入门demo就搭建好了
系统学习spring cloud: 引用github上的源码:
源码下载:https://github.com/forezp/SpringCloudLearning/tree/master/chapter1