搭建Eureka服务
文章目录
- 搭建Eureka服务
- 搭建EurekaServer
- 注册user-service
- 注册多个实例
- 在order-service中完成服务拉取和负载均衡
搭建EurekaServer
<dependency><!--eureka服务器--><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId></dependency>
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication
{public static void main( String[] args ){SpringApplication.run(EurekaApplication.class,args);}
}
server:port: 10086 # 服务端口
spring:application:name: eurekaServer # 服务名称
eureka:client:service-url: # eureka的地址信息,eureka自己也是一个微服务,eureka在启动的时候,会将自己也注册到eureka上,为了eureka做集群使用defaultZone: http://127.0.0.1:10086/eureka
注册user-service
<!-- 引入eureka客户端依赖--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>
注册多个实例
在order-service中完成服务拉取和负载均衡
package cn.itcast.order.service;import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.pojo.Order;
import cn.itcast.order.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;@Service
public class OrderService {@Autowiredprivate OrderMapper orderMapper;@Autowiredprivate RestTemplate restTemplate;public Order queryOrderById(Long orderId) {// 1.查询订单Order order = orderMapper.findById(orderId);// 2. 利用RestTemplate发起http请求,查询用户// 2.1 url路径String url = "http://userServer/user/" + order.getUserId();// 2.2 发送http请求,实现远程调用User user = restTemplate.getForObject(url, User.class);// 3. 封装user到Orderorder.setUser(user);// 4.返回return order;}
}
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
public class OrderApplication {public static void main(String[] args) {SpringApplication.run(OrderApplication.class, args);}/*** 完成创建RestTemplate,并注入容器* @return*/@Bean@LoadBalancedpublic RestTemplate restTemplate() {return new RestTemplate();}}
总结