The third stage: Day17 jsonp global exception handling mechanism httpclient SOA idea RPC calls zookeeper Dubbo

Half bump 2020-11-09 16:56:08
stage day17 day jsonp global


1.JSONP Global exception handling mechanism

1.1 Problem specification

When the back-end server execution error , Global exception handling is performed . however JSONP The call requirements of the request for return type callback(JSON) structure . So we need to reconstruct the return value structure type of global exception handling .
 Insert picture description here

1.2 Edit global exception handling mechanism

`package com.jt.aop;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.vo.SysResult;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
//@ControllerAdvice // Intercept controller layer
//@ResponseBody
@RestControllerAdvice // Defines the class for handling global exceptions AOP= Abnormal notice
public class SystemAOP {
/**
* Methods for defining global exceptions When something goes wrong , Program start execution The parameters are general class type
* If something goes wrong , You should output abnormal information , Then return the error data .
*
* Rules for solving cross domain global exception handling : Cross domain of Jingtao project is to use JSONP. http://xxxx?callback=xxxxx
* If the request contains callback Parameters Think it is JSONP Cross-domain request .
* difficulty : How to get callback What about parameters? ??/
*/
@ExceptionHandler({RuntimeException.class})
public Object systemAop(Exception e, HttpServletRequest request){
e.printStackTrace();
String callback = request.getParameter("callback");
if(StringUtils.isEmpty(callback)){
// Normal method call mode
return SysResult.fail();
}else{
// Prove to be jsonp Cross-domain request
return new JSONPObject(callback, SysResult.fail());
}
}
}`

2.HttpClient

2.1 Business needs

Business description : As some operations , Data may be processed in business , After that, the server communicates with the server .
 Insert picture description here
 Insert picture description here

2.2 HttpClient Introduce

HTTP The agreement may be now Internet Most used on 、 The most important agreement , More and more Java Applications need to go directly through HTTP Protocol to access network resources . Although in JDK Of java net Access is already provided in the package HTTP Basic functions of the protocol , But for most applications ,JDK The functions provided by the library itself are not rich and flexible enough .HttpClient yes Apache Jakarta Common Sub projects under , To provide efficient 、 Abreast of the times 、 Feature rich support HTTP Client programming toolkit for protocol , And it supports HTTP Latest version and suggestions of the agreement .HttpClient It has been applied in many projects , such as Apache Jakarta Two other open source projects famous in Cactus and HTMLUnit It's all used HttpClient. Now? HttpClient The latest version is HttpClient 4.5 .6(2015-09-11)

summary : stay java Agents can be used internally httpClient launch http Request access to the server for resources .( Tools API)

2.3 HttpClient Introductory cases

2.3.1 introduce jar package

 `<!-- add to httpClient jar package -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>`

2.3.2 Editing tests API

`package com.jt;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import java.io.IOException;
public class HttpClientTest {
/**
* requirement : stay java Inside the code , Get Baidu's page .
* Implementation steps :
* 1. Determine the target address : https://www.baidu.com/
* 2. establish httpClient Client object
* 3. Create request type
* 4. launch http request . And get the result of the response . Then judge whether the status code is 200 If it is equal to 200 The request is correct
* 5. If the request is correct, the response value information is obtained dynamically . After that, the data is processed again ....
* */
@Test
public void testGet() throws IOException {
String url = "https://www.jd.com/";
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == 200) {
// Indicates that the user request is correct
// Get the return value data
HttpEntity httpEntity = httpResponse.getEntity();
String result = EntityUtils.toString(httpEntity, "UTF-8");
System.out.println(result);
}
}
}`

2.4 HttpClient Strengthen the case

2.4.1 The case requires

Users use the web address http://www.jt.com/getItems Required httpClient The way , obtain jt-manage Product information in after json In the form of strings .
jt-web Server access jt-manage When the website http://manage.jt.com/getItems.

2.4.2 Editor's desk HttpClientController

`package com.jt.controller;
import com.jt.pojo.Item;
import com.jt.service.HttpClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class HttpClientController {
@Autowired
private HttpClientService httpClientService;
/**
* Get back end manage Product data information in
*/
@RequestMapping("/getItems")
public List<Item> getItems(){
return httpClientService.getItems();
}
}`

2.4.2 Editor's desk HttpClientService

`package com.jt.service;
import com.jt.pojo.Item;
import com.jt.util.ObjectMapperUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class HttpClientServiceImpl implements HttpClientService{
@Override
public List<Item> getItems() {
List<Item> itemList = new ArrayList<>();
//1. Define the remote access URL
String url = "http://manage.jt.com/getItems";
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == 200){
String result =
EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
//result yes jt-manage by jt-web Back to List<Item> Of JSON strand
if(!StringUtils.isEmpty(result)){
itemList = ObjectMapperUtil.toObj(result, itemList.getClass());
}
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return itemList;
}
}`

2.4.3 Editing backstage HttpClientController

`package com.jt.web.controller;
import com.jt.pojo.Item;
import com.jt.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class HttpClientController {
@Autowired
private ItemService itemService;
/**
* url Request address : http://manage.jt.com/getItems
*/
@RequestMapping("/getItems")
public List<Item> getItems(){
return itemService.getItems();
}
}`

2.4.4 Editing backstage HttpClientService

`@Override
public List<Item> getItems() {
return itemMapper.selectList(null);
}`

2.4.5 Page effect display

 Insert picture description here

  1. SOA thought ( Standards for micro service agent editing )

=====================

Service Oriented Architecture (SOA) It's a component model , It will be different functional units of the application ( It's called service ) To break up , And through well-defined interfaces and protocols between these services . Interfaces are defined in a neutral way , It should be independent of the hardware platform that implements the service 、 Operating system and programming language . This allows services built into a variety of systems to interact in a unified and common way .

 Insert picture description here

  1. RPC Introduction to ideas

===========

RPC yes Remote procedure call (Remote Procedure Call) Abbreviated form .
summary :

  1. When you can't finish a business, you can't do it directly , Business that needs help from a third party .
  2. Use RPC when " Feeling " You are calling your own methods to complete the business .

5. Micro service idea

The core : 1. Distributed thinking ( Demolition ) 2. automation (HA, automation )

5.1 Traditional project issues

1. If the nginx The way Load balancing , When the number of services changes , All have to be modified manually nginx.conf The configuration file . Not smart enough .
2. All requests will pass nginx Server as transit . If nginx Once the server goes down , It directly affects the whole system .nginx It's better to just do simple Reverse proxy that will do
The traditional way Not smart enough …

 Insert picture description here

5.2 How to call microservices

 Insert picture description here
Call step :
1. Write service information to registry (1. The service name 2. service IP Address 3. port )
2. The registry received server information , Maintain service list data dynamically .
3. When consumers start, they will link to the registry . Purpose to obtain service list data .
4. The registry will synchronize the service list data to consumers , And save it locally to consumers . It is convenient to call later .
5. When the consumer starts a business call , Load balancing will be performed according to the known service information , Visit the service provider .
6. When a service provider goes down , There is a heartbeat detection mechanism with the registry . So the list of services will be maintained dynamically .
7. When the list of services in the registry changes , It will broadcast all over the network Inform all consumers Update local service list .

5.3 Zookeeper Registration Center Introduction

ZooKeeper It's a distributed one , Open source distributed application coordination service , yes Google Of Chubby An open source implementation , yes Hadoop and Hbase Important components . It is a software that provides consistency services for distributed applications , The features provided include : Configuration maintenance 、 Domain name service 、 Distributed synchronization 、 Group service, etc .
ZooKeeper The goal is to encapsulate complex, error-prone, critical services , Will be simple to use interface and efficient performance 、 A stable system is provided to the user .
ZooKeeper Contains a simple set of primitives , Provide Java and C The interface of .
ZooKeeper In the code version , Provides distributed exclusive locks 、 The election 、 The interface of the queue , Code in $zookeeper_homesrcrecipes. The distribution locks and queues are Java and C Two versions , The election is just Java edition .
Generalization : ZK The main task is Service scheduling , The ability to provide consistency .

5.4 About cluster knowledge introduction

5.4.1 The smallest cluster units are

The formula : The number of surviving nodes > N/2 Clusters can create
1 platform : 1-1 > 1/2 fake
2 platform : 2-1> 2/2 fake
3 platform : 3-1> 3/2 correct
4 platform : 4-1> 4/2 correct

Conclusion : Build the smallest unit of a cluster 3 platform .

5.4.2 Why clusters are usually odd

  1. 3 At most, the cluster has several downtime Cluster works Most downtime 1 platform
  2. 4 At most, several clusters can work normally Most downtime 1 platform
    If you implement the same function Odd numbers are better .

5.5 About zk Cluster election rules

principle : myid Maximum priority myid The higher the value, the easier it is to be the host . More than half of them agree to be elected host
subject : ask 1,2,3,4,5,6,7 Start in turn ask 1: Who is the host 4 When the host
ask 2: Who can never be elected host ??? 1 2 3

6 Homework

preview Dubbo frame
Modify the code :
Modify the entry case dubbo Project pom.xml file
 Insert picture description here

 `1. Project version `

 Insert picture description here
2. modify module label
 Insert picture description here
3. Import the project
take dubbo-jt Paste project to workspace and jt Level Then right click add Maven…
 Insert picture description here

版权声明
本文为[Half bump]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple