SpringCloud Ribbon负载均衡代码实例
1.添加依赖
org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-netflix-ribbon org.projectlombok lombok true
2.修改启动类
importorg.mybatis.spring.annotation.MapperScan; importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.cloud.client.loadbalancer.LoadBalanced; importorg.springframework.context.annotation.Bean; importorg.springframework.web.client.RestTemplate; @SpringBootApplication @MapperScan("cn.ytheng.order_service") publicclassOrderServiceApplication{ /** *@Loadbalanced负载均衡策略 */ @Bean @LoadBalanced publicRestTemplaterestTemplate(){ returnnewRestTemplate(); } publicstaticvoidmain(String[]args){ SpringApplication.run(OrderServiceApplication.class,args); } }
3.添加Controller
importcn.theng.order_service.utils.RibbonUtils; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.cloud.client.ServiceInstance; importorg.springframework.cloud.client.loadbalancer.LoadBalancerClient; importorg.springframework.util.LinkedMultiValueMap; importorg.springframework.web.bind.annotation.PostMapping; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestParam; importorg.springframework.web.bind.annotation.RestController; importorg.springframework.web.client.RestTemplate; importjava.util.HashMap; importjava.util.Map; @RestController @RequestMapping("/api/v1/order") publicclassProductOrderController{ @RequestMapping("/test") publicObjecttest(@RequestParam("product_id")intproductId){ //方法一 //ServiceInstanceinstance=loadBalancerClient.choose("product-service"); //Stringurl=String.format("http://%s:%s/api/v1/product/find?id="+productId,instance.getHost(),instance.getPort()); //RestTemplatetemplate=newRestTemplate(); //Mapmap2=template.getForObject(url,Map.class); //负载均衡 //商品列表启用两个节点时 //由客户端来自动选择节点,可能是8771端口,也有可能是8772端口 //参数id名称需要保持一致 //方法二(推荐) Stringuri="http://product-service/api/v1/product/find?id={id}"; Map request=newHashMap<>(); request.put("id",productId); Map map3=RibbonUtils.get(uri,Map.class,request); return"success"; } @PostMapping("/test2") publicObjecttest2(@RequestParam("product_id")intproductId){ Productproduct=newProduct(); product.setId(productId); Stringuri="http://product-service/api/v1/product/find2"; LinkedMultiValueMap headers=newLinkedMultiValueMap<>(); headers.add("token","theng"); Objectresult=RibbonUtils.post(uri,Object.class,product,headers); return"success"; } }
4.添加Ribbon调用公共类
importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.http.*; importorg.springframework.stereotype.Component; importorg.springframework.util.LinkedMultiValueMap; importorg.springframework.web.client.RestTemplate; importjavax.annotation.PostConstruct; importjava.util.Arrays; importjava.util.Collections; importjava.util.Map; @Component publicclassRibbonUtils{ @Autowired privateRestTemplaterestTemplate; privatestaticRestTemplatetemplate; //@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次 @PostConstruct publicvoidinit(){ template=restTemplate; } /** * *@paramuri接口地址 *@paramresponseType返回类型 * **/ publicstaticTget(Stringuri,Class responseType){ returntemplate.getForObject(uri,responseType); } /** * *@paramuri接口地址 *@paramresponseType返回类型 *@paramrequest传递参数 * **/ publicstatic Tget(Stringuri,Class responseType,Map request){ returntemplate.getForObject(uri,responseType,request); } /** * *@paramuri接口地址 *@paramresponseType返回类型 *@paramrequest传递参数 *@paramheaderMap报头信息 * **/ publicstatic Tget(Stringuri,Class responseType,Map request,Map headerMap){ //添加报头 HttpHeadersheaders=newHttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); for(Map.Entry entry:headerMap.entrySet()){ StringmapKey=entry.getKey(); StringmapValue=entry.getValue(); headers.add(mapKey,mapValue); } //body的类型定为String,这里使用get没有用到body,post会使用到 HttpEntity entity=newHttpEntity (null,headers); ResponseEntity result=template.exchange(uri,HttpMethod.GET,entity,responseType,request); returnresult.getBody(); } /** * *@paramuri接口地址 *@paramresponseType返回类型 *@parambody传递实体 *@paramheaders报头信息 * **/ publicstatic Tpost(Stringuri,Class responseType,Objectbody,LinkedMultiValueMap headers){ if(!headers.containsKey("Content-Type")){ headers.put("Content-Type",Collections.singletonList("application/json;charset=UTF-8")); } HttpEntityrequest=newHttpEntity(body,headers); Objectobj=template.postForObject(uri,request,responseType); return(T)obj; } }
5.在PostMan上测试两个接口即可
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。