1、为什么HTTP连接池能提升系统性能?
我们都了解过线程池、数据库连接池等;它的好处是避免了频繁的创建连接和销毁的步骤。首先我们知道HTTP连接需要经过三次握手,四次挥手的过程,这是很耗费性能的;所以HTTP连接池帮助我们节省了这一步,提高了吞吐量。
2、Feign是如何解决以上问题的?
首先Feign的HTTP客户端支持三种框架:HttpURLConnection、HttpClient、OkHttp;默认是HttpURLConnection
1、HttpURLConnection是JDK自带的,不支持连接池,如果要实现连接池机制,还需要自己编写代码,问题是你能写好底层代码吗?
2、HttpClient封装了一系列的HTTP属性,基于池的概念,不仅提高了开发效率,也提高了代码的健壮性。看!这是大佬写的
3、代码实现
1、添加依赖
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
注意在springcloud Hoxton SR1以后版本已经集成了HttpClient的包(包过此版本)
2、开启httpclient
feign:
httpclient:
enabled: true #开启httpclient
3、业务编码
consumer 模块
@RestController
public class ProductController {
@Resource
private ProductService productService;
@GetMapping(value = "/product/object")
public Product selectProductByObject(Product product) {
return productService.selectProductByObject(product);
}
}
@FeignClient(value = "service-provider")
public interface ProductService {
/* @GetMapping(value = "/product/list")
List<Product> selectProductList();
@GetMapping(value = "/product/{id}")
Product selectProductById(@PathVariable("id") Integer id);*/
@GetMapping(value = "/product/object")
Product selectProductByObject(Product product);
}
provider模块
@RestController
@RequestMapping(value = "/product")
public class ProductController {
@Resource
private ProductService productService;
/* @GetMapping(value = "/list")
public List<Product> getProductList() throws InterruptedException {
return productService.selectProductList();
}
@GetMapping(value = "/{id}")
public Product selectProductById(@PathVariable("id") Integer id) {
return productService.selectProductById(id);*/
}
@GetMapping(value = "/object")
public Product selectProductByObject(@RequestBody Product product) {
return productService.selectProductByObject(product);
}
}
public interface ProductService {
/* List<Product> selectProductList() throws InterruptedException;
Product selectProductById(Integer id);*/
Product selectProductByObject(Product product);
}
@Service
public class ProductServiceImpl implements ProductService {
/* @Override
public List<Product> selectProductList() {
return Arrays.asList(
new Product(1, "华为!", 100, 2999.0),
new Product(2, "xiaomi", 99, 1999.0),
new Product(3, "vivo", 102, 2999.0)
);
}
@Override
public Product selectProductById(Integer id) {
return new Product(id, "RPC", 1, 100D);*/
}
@Override
public Product selectProductByObject(Product product) {
return product;
}
}
4、测试
5、总结
转载:https://blog.csdn.net/Kevinnsm/article/details/117262056
查看评论