SpringCloud Ribbon負(fù)載均衡代碼實(shí)例
1.添加依賴
<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> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
2.修改啟動(dòng)類
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@MapperScan("cn.ytheng.order_service")
public class OrderServiceApplication {
/**
* @Loadbalanced負(fù)載均衡策略
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
3.添加Controller
import cn.theng.order_service.utils.RibbonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/order")
public class ProductOrderController {
@RequestMapping("/test")
public Object test(@RequestParam("product_id") int productId) {
//方法一
// ServiceInstance instance = loadBalancerClient.choose("product-service");
// String url = String.format("http://%s:%s/api/v1/product/find?id=" + productId, instance.getHost(), instance.getPort());
// RestTemplate template = new RestTemplate();
// Map<String, Object> map2 = template.getForObject(url, Map.class);
//負(fù)載均衡
//商品列表啟用兩個(gè)節(jié)點(diǎn)時(shí)
//由客戶端來(lái)自動(dòng)選擇節(jié)點(diǎn),可能是8771端口,也有可能是8772端口
//參數(shù)id名稱需要保持一致
//方法二(推薦)
String uri = "http://product-service/api/v1/product/find?id={id}";
Map<String, Object> request = new HashMap<>();
request.put("id", productId);
Map<String, Object> map3 = RibbonUtils.get(uri, Map.class, request);
return "success";
}
@PostMapping("/test2")
public Object test2(@RequestParam("product_id") int productId) {
Product product = new Product();
product.setId(productId);
String uri = "http://product-service/api/v1/product/find2";
LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("token", "theng");
Object result = RibbonUtils.post(uri, Object.class, product, headers);
return "success";
}
}
4.添加Ribbon調(diào)用公共類
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
@Component
public class RibbonUtils {
@Autowired
private RestTemplate restTemplate;
private static RestTemplate template;
//@PostConstruct修飾的方法會(huì)在服務(wù)器加載Servlet的時(shí)候運(yùn)行,并且只會(huì)被服務(wù)器調(diào)用一次
@PostConstruct
public void init() {
template = restTemplate;
}
/**
*
* @param uri 接口地址
* @param responseType 返回類型
*
* */
public static <T> T get(String uri, Class<T> responseType) {
return template.getForObject(uri, responseType);
}
/**
*
* @param uri 接口地址
* @param responseType 返回類型
* @param request 傳遞參數(shù)
*
* */
public static <T> T get(String uri, Class<T> responseType, Map<String, ?> request) {
return template.getForObject(uri, responseType, request);
}
/**
*
* @param uri 接口地址
* @param responseType 返回類型
* @param request 傳遞參數(shù)
* @param headerMap 報(bào)頭信息
*
* */
public static <T> T get(String uri, Class<T> responseType, Map<String, ?> request, Map<String, String> headerMap) {
//添加報(bào)頭
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
for(Map.Entry<String, String> entry : headerMap.entrySet()){
String mapKey = entry.getKey();
String mapValue = entry.getValue();
headers.add(mapKey, mapValue);
}
//body的類型定為String,這里使用get沒(méi)有用到body,post會(huì)使用到
HttpEntity<String> entity = new HttpEntity<String>(null, headers);
ResponseEntity<T> result = template.exchange(uri, HttpMethod.GET, entity, responseType, request);
return result.getBody();
}
/**
*
* @param uri 接口地址
* @param responseType 返回類型
* @param body 傳遞實(shí)體
* @param headers 報(bào)頭信息
*
* */
public static <T> T post(String uri, Class<T> responseType, Object body, LinkedMultiValueMap<String, String> headers) {
if (!headers.containsKey("Content-Type")) {
headers.put("Content-Type", Collections.singletonList("application/json;charset=UTF-8"));
}
HttpEntity request = new HttpEntity(body, headers);
Object obj = template.postForObject(uri, request, responseType);
return (T) obj;
}
}
5.在PostMan上測(cè)試兩個(gè)接口即可

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 詳解SpringCloud Ribbon 負(fù)載均衡通過(guò)服務(wù)器名無(wú)法連接的神坑
- Springcloud ribbon負(fù)載均衡算法實(shí)現(xiàn)
- SpringCloud 服務(wù)負(fù)載均衡和調(diào)用 Ribbon、OpenFeign的方法
- SpringCloud手寫(xiě)Ribbon實(shí)現(xiàn)負(fù)載均衡
- SpringCloud 2020-Ribbon負(fù)載均衡服務(wù)調(diào)用的實(shí)現(xiàn)
- springcloud中Ribbon和RestTemplate實(shí)現(xiàn)服務(wù)調(diào)用與負(fù)載均衡
- SpringCloud?Ribbon負(fù)載均衡原理
相關(guān)文章
Spring?IOC?xml方式進(jìn)行工廠Bean操作詳解
這篇文章主要介紹了Spring?IOC?xml方式進(jìn)行工廠Bean操作,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2023-01-01
Java通過(guò)Fork/Join優(yōu)化并行計(jì)算
這篇文章主要為大家詳細(xì)介紹了Java通過(guò)Fork、Join來(lái)優(yōu)化并行計(jì)算,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04
SpringBoot集成Kafka 配置工具類的詳細(xì)代碼
spring-kafka 是基于 java版的 kafka client與spring的集成,提供了 KafkaTemplate,封裝了各種方法,方便操作,它封裝了apache的kafka-client,不需要再導(dǎo)入client依賴,這篇文章主要介紹了SpringBoot集成Kafka 配置工具類,需要的朋友可以參考下2022-09-09
SpringBoot+MybatisPlus+Mysql+JSP實(shí)戰(zhàn)
這篇文章主要介紹了SpringBoot+MybatisPlus+Mysql+JSP實(shí)戰(zhàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
詳解Maven profile配置管理及激活profile的幾種方式
這篇文章主要介紹了詳解Maven profile配置管理及激活profile的幾種方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
手把手教你在eclipse創(chuàng)建第一個(gè)java?web項(xiàng)目并運(yùn)行
Eclipse是用來(lái)做開(kāi)發(fā)的自由集成開(kāi)發(fā)環(huán)境,這也是很多java程序員會(huì)使用的開(kāi)發(fā)環(huán)境,所以可以使用eclipse創(chuàng)建javaweb項(xiàng)目,下面這篇文章主要給大家介紹了關(guān)于如何在eclipse創(chuàng)建第一個(gè)java?web項(xiàng)目并運(yùn)行的相關(guān)資料,需要的朋友可以參考下2023-02-02
Intellij IDEA中啟動(dòng)多個(gè)微服務(wù)(開(kāi)啟Run Dashboard管理)
這篇文章主要介紹了Intellij IDEA中啟動(dòng)多個(gè)微服務(wù)(開(kāi)啟Run Dashboard管理),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07

