<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
导入Eureka服务端依赖,建立注册中心
配置注册中心
#设置Eureka端口
server:
port: 8081
# 应用名称/服务名
spring:
application:
name: eurekaserver
eureka:
client:
#false表示不向注册中心注册自己
register-with-eureka: false
#false表示自己端就是注册中心,我的职责就是维护实例,并不需要去检索服务
fetch-registry: false
#设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
#eureka服务端的实例名称
instance:
hostname: localhost
添加@EnableEurekaServer注解到springboot项目启动类
表示此模块是注册中心
启动服务
在网页输入:http://localhost:10086/进入注册中心
服务列表参数
配置Eureka客户端
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置服务注册信息
服务注册
#设置Eureka端口
server:
port: 6666
# 应用名称/服务名
spring:
application:
name: eurekaorder
eureka:
client:
#表示是否将自己注册进Eureka,默认为true
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息,默认为true
fetch-registry: true
#向服务注册中心注册自己(此处为注册中心地址)
service-url:
defaultZone: http://localhost:10086/eureka/
instance:
#更改主机实例ID名
instance-id: ${spring.application.name}:${server.port}
#鼠标悬停时显示主机ip地址
prefer-ip-address: true
添加@EnableEurekaClient注解到springboot项目启动类
idea如何显示springboot多服务启动状况
实现服务多实例
跨服务的远程调用
在启动类中创建RestTemplate对象注入ioc容器中
//使用RestTemplate实现跨服务的远程调用
//向其他服务发送HTTP请求
@Bean
@LoadBalanced//负载均衡注解
public RestTemplate restTemplate(){
return new RestTemplate();
}
服务拉取
@RestController
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/order")
public String hello(){
//url=user服务的服务名/应用名称+请求路径
String url="http://eurekuser/user";
/**
* 发布http请求实现远程调用
* 参数1:跨服务的请求路径
* 参数2:返回值类型
*/
String user = restTemplate.getForObject(url, String.class);
return "hellorder"+user;
}
}