本篇博文延续:
SpringCloud 详细教程(1) 搭建多模块开发环境 进行引入。
1. 修改父模块cloud_parent 配置
-
在 cloud_parent 的pom.xml 中添加 一下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>
<!--Spring Cloud 服务注册组件 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2.修改子模块 eureka-server 配置
-
修改 eureka-server 的application.properties文件
spring.application.name=eureka-server
server.port=9000
eureka.instance.hostname=localhost
#表示是否将自己注册到Eureka Server,默认为true
eureka.client.register-with-eureka=false
#表示是否从Eureka Server获取注册信息,默认为true
eureka.client.fetch-registry=false
- 在eureka-server 的 启动类中添加:
@EnableEurekaServer
3.修改子模块 eureka-client 配置
- 修改eureka-client 模块的配置文件application.properties,添加如下配置:
spring.application.name=eureka-client
server.port=9001
eureka.client.serviceUrl.defaultZone=http://localhost:9000/eureka/
- 在eureka-client 模块中创建 包和测试类
package com.hf.client.eureka_client.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description:
* @author: YaoGuangXun
* @date: 2019/2/28 14:18
* @Version: 1.0
*/
@RestController
public class TestController {
@RequestMapping(value = "index",method = RequestMethod.GET)
public String test(){
return "Hello SpringCloud";
}
}
结构如图
- 在eureka-client 的 启动类添加注解
@EnableDiscoveryClient
如图
4.修改子模块 eureka_feign 配置
-
在eureka_feign 模块的pom.xml中添加 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 修改eureka_feign 的配置文件application.properties,添加如下配置:
spring.application.name=eureka-feign
server.port=9002
eureka.client.serviceUrl.defaultZone=http://localhost:9000/eureka/
- 在eureka_feign 的启动类中添加注解:
@EnableFeignClients
@EnableDiscoveryClient
- 新建feign和controller 包
- 添加接口类TestInterface
@FeignClient(name = "eureka-client")
public interface TestInterface {
@GetMapping(value = "/index")
String get();
}
- 添加控制类TestController
@RestController
public class TestController {
@Autowired
TestInterface testInterface;
@GetMapping("/getByIndex")
public String get() {
return testInterface.get();
}
}
5. 项目结构
- 整个项目的目录结构如下:
6.测试项目
- 测试 依次启动 eureka_server, eureka_client, eureka_feign
浏览器访问:http://localhost:9000/
如上图 表明注册中心成功启动。
浏览器访问:http://localhost:9001/index
如上图,表明服务提供者启动正常
浏览器访问:http://localhost:9002/getByIndex
如上图,表明服务消费者启动正常