SpringCloud
1.概述
为微服务架构中涉及的服务治理、断路器、负载均衡、配置管理、控制总线和集群状态管理等操作提供了一种简单的开发方式
- 与SpringBoot的区别
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2fa05365cf7264d58ae52bd6c0aaf544.png)
- Rest风格
请求:http://localhost:8080/product/get/1
原来写法:http://localhost:8080/product?pid=1
2.生态简介
- 外部或者内部的非SpringCloud项目都统一通过API网关(Zuul)来访问内部服务
- 网关接收到请求后,从注册中心(Eureka)获取可用服务
- 由Ribbon均衡负载后,分发到后端的具体实例
- 微服务之间通过Feign进行通信处理业务
- Hystrix负责处理服务超时熔断
- Turbine监控服务间的调用和熔断相关指标
实现通信
1.接受请求(rest风格)
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductBiz productBiz;
@RequestMapping("/get/{pid}")
public JsonModel get(@PathVariable("pid") Integer pid, JsonModel jsonModel) {
Product product = this.productBiz.findById(pid);
jsonModel.setCode(1);
jsonModel.setData(product);
return jsonModel;
}
@RequestMapping("/add")
public JsonModel add(@RequestBody Product product, JsonModel jsonModel) {
this.productBiz.add(product);
jsonModel.setCode(1);
return jsonModel;
}
@RequestMapping("/list")
public JsonModel list(JsonModel jsonModel) {
List<Product> list = this.productBiz.findByList();
jsonModel.setCode(1);
jsonModel.setData(list);
return jsonModel;
}
}
2.发送请求(消费端)到另一个地址获取响应
private final String BASE_URL_GET = "http://localhost:8081/product/get/";
@RequestMapping("/product/get/{pid}")
public JsonModel get(@PathVariable("pid") Integer pid, JsonModel jsonModel) throws IOException {
String url = BASE_URL_GET + pid;
jsonModel = sendRequest(url);
return jsonModel;
}
private JsonModel sendRequest(String urlstr) throws IOException {
JsonModel jsonModel = new JsonModel();
String result = "";
StringBuffer sb = new StringBuffer();
URL url = new URL(urlstr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStream iis = con.getInputStream();
byte[] bs = new byte[100 * 1024];
int length = -1;
while ((length = iis.read(bs, 0, bs.length)) != -1) {
result = new String(bs, 0, length);
sb.append(result);
}
Gson g = new Gson();
jsonModel = g.fromJson(sb.toString(), JsonModel.class);
iis.close();
return jsonModel;
}
- Spring封装好的RestTemplate对象(最易)
@Configuration
public class WebConfigs {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
------------------------------------------------
private final String BASE_URL_GET = "http://localhost:8081/product/get/";
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/product/get/{pid}")
public JsonModel get(@PathVariable("pid") Integer pid, JsonModel jsonModel) throws IOException {
String url = BASE_URL_GET + pid;
jsonModel = this.restTemplate.getForObject(url, JsonModel.class);
return jsonModel;
}
- Apache的Http Client
- Netty的异步Http Client
- Feign(最优)