使用idea搭建spring cloud 项目
1、先创建一个maven项目
项目结构如下:
2、创建Eureka
在项目上右键–>new–>module–>Spring Initializr–>next
点击next
点击next=>finish。
此时等待下载依赖,修改配置。
启动类下加注解@EnableEurekaServer。
修改application.yml
# 服务注册中心 (单节点)
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
fetch-registry: false # 表示是否从Eureka Server获取注册信息,默认为true.因为这是一个单点的Eureka Server,不需要同步其他的Eureka Server节点的数据,这里设置为false
register-with-eureka: false # 表示是否将自己注册到Eureka Server,默认为true.由于当前应用就是Eureka Server,故而设置为false.
service-url:
# 设置与Eureka Server的地址,查询服务和注册服务都需要依赖这个地址.默认是http://localhost:8761/eureka/;多个地址可使用','风格.
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
启动项目成功后,验证成功访问http://localhost:8761/。
3、创建EurekaProducer
在项目上右键–>new–>module–>Spring Initializr–>next
选择项目需要依赖
next=》finish。
启动类加@EnableEurekaClient。
修改yml文件:
server:
port: 8765
spring:
application:
name: eureka-producer
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka # 指定服务注册中心
启动项目,启动成功访问注册中心:
4、创建 consumer 。
在项目上右键–>new–>module–>Spring Initializr–>next
同第三步,修改名字 producer改成consumer。
选择依赖:
启动类加
@EnableDiscoveryClient
yml修改:
server:
port: 8763
spring:
application:
name: eureka-consumer
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka # 指定服务注册中心
配置完毕以后,启动服务consumer,刷新Eureka控制台,可以看到consumer已经注册。
5、测试
consumer启动类加入restTemplate消费服务
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
consumer 中添加controller类
@RestController
public class testController {
@Autowired
RestTemplate restTemplate;
@RequestMapping("test")
public String test(@RequestParam String name){
return restTemplate.getForObject("http://EUREKA-PRODUCER/test?param=" + name, String.class);
}
}
producer 启动类
@SpringBootApplication
@EnableEurekaClient
@RestController
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerApplication.class, args);
}
@RequestMapping("test")
public String test(String param){
return "hello"+ param;
}
}
启动所有项目 访问http://localhost:8763/test?name=eureka