Spring Cloud 项目搭建
- 搭建eureka注册中心
首先先搭建一个SpringBoot项目,引入springboot依赖
在pom.xml文件添加eureka依赖
<!-- springboot2.x 对应的eureka依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
添加SpringCloud版本管理(因为我的SpringBoot版本是2.4.4,所以我的SpringCloud版本采用2020.0.0,否则启动会报错)
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2020.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!-- maven中找不到,需要从这个地址中下载 -->
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
在application.properties添加
#内嵌定时tomcat 的端口
server.port=8083
#设置该服务注册中心的hostname
eureka.instance.hostname=localhost
#由于我们目前创建的是一个服务注册中心,默认情况下,这个应用会想注册中心(也就是他自己)注册他自己
#设置为false表示禁止这种自己向自己注册的默认行为
eureka.client.register-with-eureka=false
#表示不去检索其他的服务,因为服务注册中心本身的职责就是维护服务实例,它不需要去检索其他服务
eureka.client.fetch-registry=false
#制定服务注册中心的位置
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka
最后在启动类开启eureka注册中心服务器
@SpringBootApplication
@EnableEurekaServer //开启Eureka注册中心服务器
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
启动项目,查看eureka注册页面
- 创建eureka客户端provider提供者
在pom.xml中添加eureka客户端依赖
<!-- springboot2.x 对应的eureka依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置文件application.properties 添加
server.port=8080
#配置服务的名称
spring.application.name=01-provider
#eureka连接地址
eureka.client.service-url.defaultZone=http://localhost:8083/eureka
启动类开启eureka客户端功能
@SpringBootApplication
@EnableEurekaClient //开启eureka客户端功能
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
启动项目,观察eureka注册中心是否有客户端注册
- 使用Ribbon 从eureka服务注册中心发现服务消费者
pom.xml文件的配置与提供者配置项目,不再赘述
application.properties 文件配置也与提供者相同
server.port=8081
#配置服务的名称
spring.application.name=02-consumer
#eureka连接地址
eureka.client.service-url.defaultZone=http://localhost:8083/eureka
接下来在我们创建的模版中添加Ribbon负载均衡注解
@Configuration
public class BeanConfig {
@LoadBalanced //Ribbon 负载均衡
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
接下来我们访问提供者不再使用IP和端口,使用服务名称即可
@RestController
public class ConsumerController {
@Autowired
public RestTemplate restTemplate;
@RequestMapping("/consumer/hello")
public String hello(){
//采用服务名称访问
return restTemplate.getForEntity("http://01-PROVIDER/hello",String.class).getBody();
}
}
启动项目,访问消费者,结果:调用成功,返回提供者接口结果
记录文章为自学所用,也欢迎大家共同交流!!!