1、创建order_service项目
pom依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency>
yml配置:
server: port: 8781 #指定注册中心地址 eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ #服务的名称 spring: application: name: order-service
2、开发伪下单接口
@Service public class ProductOrderServiceImpl implements ProductOrderService { @Autowired private RestTemplate restTemplate;
// @Autowired, 启动时注入
private LoadBalancerClient loadBalancer;
@Override public ProductOrder save(int userId, int productId) {
//从注册中心拉取product-service列表调用其url为api/v1/product/find 接口
Map<String,Object> productMap = restTemplate.getForObject("http://product-service/api/v1/product/find?id="+productId, Map.class);
//调用方式二
// ServiceInstance instance = loadBalancer.choose("product-service");
// String url = String.format("http://%s:%s/api/v1/product/find?id="+productId, instance.getHost(),instance.getPort());
// RestTemplate restTemplate = new RestTemplate();
// Map<String,Object> productMap = restTemplate.getForObject(url, Map.class);
ProductOrder productOrder = new ProductOrder();
productOrder.setCreateTime(new Date());
productOrder.setUserId(userId);
productOrder.setTradeNo(UUID.randomUUID().toString());
productOrder.setProductName(productMap.get("name").toString());
productOrder.setPrice(Integer.parseInt(productMap.get("price").toString()));
return productOrder; } }
3、使用ribbon. (类似httpClient,URLConnection),客户端负载均衡
启动类增加注解
@SpringBootApplication public class OrderServiceApplication { public static void main(String[] args) { SpringApplication.run(OrderServiceApplication.class, args); } //分析@LoadBalanced
//1)首先从注册中心获取provider的列表
//2)通过一定的策略选择其中一个节点
//3)再返回给restTemplate调用 //Ribbon自带负载均衡bean @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }
4、根据名称进行调用商品,获取商品详情
@RestController @RequestMapping("api/v1/order") public class OrderController { @Autowired private ProductOrderService productOrderService; @RequestMapping("save") public Object save(@RequestParam("user_id")int userId, @RequestParam("product_id") int productId){ return productOrderService.save(userId, productId); } }
启动 eureka, order-service, 以及多个 Product-service实例,会轮询从Product-service实例调用服务,实现负载均衡。
若想要自定义负载均衡,则可在order-service yml加入
#自定义负载均衡策略 product-service: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule