<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
<!-- 引入eureka客户端依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
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 { @Autowired private OrderMapper orderMapper; @Autowired private 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到Order order.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 @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }
总结