Eureka服务
- 搭建EurekaServer
- 服务注册
- 服务发现
需要有一个注册服务的module。
引入maven依赖,添加server启动类注解,注册url和端口号之后,服务端搭建完成。
<!--eureka服务端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
server:
port: 10086 #服务端口
spring:
application:
name: eurekaserver #服务名称
eureka:
client:
service-url: # eureka地址信息
defaultZone: http://127.0.0.1:10086/eureka
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
其他模块如果需要使用微服务调用http请求获取其他服务的功能,需要先在eureka服务端进行注册,然后即可通过eureka调用其他模块的服务。注册的步骤是,引入依赖,再添加注册配置信息。
<!--eureka客户端依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
spring:
application:
name: orderservice #服务名称
eureka:
client:
service-url: # eureka地址信息
defaultZone: http://127.0.0.1:10086/eureka
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
/**
* 创建RestTemplate对象,注入spring容器
* @return
*/
@Bean
@LoadBalanced //负载均衡
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
public Order queryOrderById(Long orderId) {
// 1.查询订单
Order order = orderMapper.findById(orderId);
// 2.利用restemplate发起http请求,查询用户
// 2.1 url路径
String url = "http://userservice/user/" + order.getUserId();
// 2.2 发送http请求,实现远程调用
User user = restTemplate.getForObject(url, User.class);
// 3.封装user对象到order
order.setUser(user);
// 4.返回
return order;
}