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. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云