畅聊架构 2019-10-20
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
ConfigBean代码
说明:主要代码,获取RestTemplate时,添加@LoadBalanced注解实现客户端负载均衡
package com.thr.springcloud.cfgbean; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.RandomRule; /** * 注解@Configuration说明:相当于spring的applicationContext.xml * 即此时加了@Configuration注解的CfgBean类 等同于 applicationContext.xml * @author xiongxiaomeng */ @Configuration public class CfgBean { /** * 使用RestTemplate调用Rest服务 * @LoadBalanced 获取RestTemplate时,加入Ribbon的负载均衡的配置 * @return Rest服务调用模板 */ @Bean @LoadBalanced public RestTemplate getRestTemplate() { return new RestTemplate(); } /** * 定义负载均衡算法: * 默认:轮询,当前改成:随机 * @return 随机算法 */ @Bean public IRule myRule() { return new RandomRule(); } }
package com.thr.springcloud.controller; import java.util.List; 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.RestController; import org.springframework.web.client.RestTemplate; import com.thr.springcloud.entities.User; /** * 消费者端的RestController * 消费者端 都是 调用服务提供者的Controller,这里使用RestTemplate的方式调用 * @author xiongxiaomeng * */ @RestController public class UserController_Consumer { //未加入Eureka+Ribbon之前,采用ip+端口的访问方式 //private static final String REST_URL_PREFIX = "http://localhost:8001"; //加入Eureka+Ribbon之后,可以直接采用服务名的调用方式,无须再使用ip+端口的调用方式 private static final String REST_URL_PREFIX = "http://THRCLOUD-DEPT"; //使用restTemplate访问restful接口非常的简单粗暴无脑。(url, requestMap, ResponseBean.class)这三个参数分别代表 @Autowired private RestTemplate _restTemplate; @RequestMapping(value="/consumer/user/add") public boolean add(User user) { return _restTemplate.postForObject(REST_URL_PREFIX + "/user/add", user, Boolean.class); } @RequestMapping(value="/consumer/user/get/{userId}") public User get(@PathVariable("userId") Long userId) { return _restTemplate.getForObject(REST_URL_PREFIX + "/user/get/" + userId, User.class); } @SuppressWarnings("unchecked") @RequestMapping(value="/consumer/user/list") public List<User> list() { return _restTemplate.getForObject(REST_URL_PREFIX + "/user/list", List.class); } @RequestMapping(value="/consumer/user/discovery") public Object discovery() { return _restTemplate.getForObject(REST_URL_PREFIX + "/user/discovery", Object.class); } }