1. 什么是负载均衡?
负载均衡,就是分发请求流量到不同的服务器。
负载均衡一般分为两种
1. 服务器端负载均衡(nginx)
2. 客户端负载均衡(Ribbon)
2. 服务提供者(spring-cloud-provider)
实体类User:
package com.wangx.cloud.model;import java.util.Date;
public class User { private Integer id; private String name; private Date date; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", date=" + date + '}'; } }
Controller接口:
package com.wangx.cloud.controller;import com.wangx.cloud.model.User;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.Date; @RestController @RequestMapping("/api/user") public class UserController { @RequestMapping(value = "/{id}", method = RequestMethod.GET) public User view(@PathVariable int id) { User user = new User(); user.setId(id); user.setName("小张"); user.setDate(new Date()); System.out.println(user); return user; } }
3. 服务消费者(spring-cloud-consumer)
package com.wangx.cloud.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController @RequestMapping(value = "/user", method = RequestMethod.POST) public class UserController { private static final String URL = "http://localhost:7777/api/user/{id}"; @Autowired private RestTemplate restTemplate; @RequestMapping(value = "/{id}", method = RequestMethod.GET) public String get(@PathVariable(value = "id") int id) { return restTemplate.getForObject(URL, String.class, id); } }
分别查看两个服务是否能正常调用。
4. 如何通过Ribbon进行调用
1. 在创建RestTemplate bean的方法上添加注解@LoadBalanced
@Bean@LoadBalanced //默认的负载策略是轮询算法public RestTemplate restTemplate() {return new RestTemplate(); }
2. 修改调用的URL为URL=http://spring-cloud-provider/api/user/{id}
注意:控制台的应用名为大写,我们统一为小写,更不能大小写都存在
5. 如何实现负载均衡
启动多个提供者,进行测试
为了区分,可以修改实体类User的name属性,
注意:修改应用的时候,端口也要修改
6. 结论
1. Ribbon通过@LoadBalanced进行负载均衡
2. 默认的负载策略是轮询算法
原文 SpringCloud学习笔记(6)----Spring Cloud Netflix之负载均衡-Ribbon的使用