Phase 3: day18 Dubbo completes user registration / single sign on

Half bump 2020-11-09 16:55:55
phase day18 day dubbo completes


  1. Dubbo

=========

1.1 Dubbo Introduce

Apache Dubbo |ˈdʌbəʊ| It's a high performance 、 Lightweight open source Java RPC frame , It provides three core competencies : Interface oriented remote method call , Intelligent fault tolerance and load balancing , And automatic service registration and discovery .
 Insert picture description here

1.2 Dubbo characteristic

 Insert picture description here

2 Dubbo Introductory cases

2.1 Define a common interface project

explain : Interface projects generally define common parts , And being relied on by third parties .
 Insert picture description here

2.2 Introduction to service providers

2.2.1 Provider code structure

 Insert picture description here

2.2.2 Edit implementation class

`package com.jt.dubbo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;
import com.jt.dubbo.mapper.UserMapper;
import com.jt.dubbo.pojo.User;
@Service(timeout=3000) //3 Second timeout Internally implemented rpc
//@org.springframework.stereotype.Service// Give the object to spring Container management
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
System.out.println(" I was the first service provider ");
return userMapper.selectList(null);
}
@Override
public void saveUser(User user) {
userMapper.insert(user);
}
}`

2.2.3 Edit provider profile

`server:
port: 9000 # Define port
spring:
datasource:
# introduce druid data source
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/jtdb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
username: root
password: root
# About Dubbo To configure
dubbo:
scan:
basePackages: com.jt # Appoint dubbo The package path of scanning dubbo annotation
application: # apply name
name: provider-user # An interface corresponds to a service name An interface can have multiple implementations
registry: # Registry Center The user gets the data from the machine The host is only responsible for monitoring the entire cluster Data synchronization
address: zookeeper://192.168.126.129:2181?backup=192.168.126.129:2182,192.168.126.129:2183
protocol: # Designated agreement
name: dubbo # Use dubbo agreement (tcp-ip) web-controller Call directly sso-Service
port: 20880 # Each service has its own specific port Can't repeat .
mybatis-plus:
type-aliases-package: com.jt.dubbo.pojo # Configure alias package path
mapper-locations: classpath:/mybatis/mappers/*.xml # add to mapper The mapping file
configuration:
map-underscore-to-camel-case: true # Turn on hump mapping rules `

2.3 Introduction to service consumers

2.3.1 edit Controller

`package com.jt.dubbo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.dubbo.pojo.User;
import com.jt.dubbo.service.UserService;
@RestController
public class UserController {
// utilize dubbo To create a proxy object for the interface utilize rpc call
@Reference
private UserService userService;
/**
* Dubbo Framework call features : long-range RPC Calling is as simple as calling your own local service
* @return
*/
@RequestMapping("/findAll")
public List<User> findAll(){
// The object data passed on a remote call must be serialized .
return userService.findAll();
}
@RequestMapping("/saveUser/{name}/{age}/{sex}")
public String saveUser(User user) {
userService.saveUser(user);
return " The user has entered the database successfully !!!";
}
}`

2.3.2 edit YML The configuration file

`server:
port: 9001
dubbo:
scan:
basePackages: com.jt
application:
name: consumer-user # Define the consumer name
registry: # Address of Registration Center
address: zookeeper://192.168.126.129:2181?backup=192.168.126.129:2182,192.168.126.129:2183`

2.3.3 Dubbo Entry case testing

 Insert picture description here

2.4 About Dubbo Framework knowledge point

2.4.1 problem 1: If one of the servers goes down Whether user access is limited ?

answer : because zk With the help of the , Make programs always have access to the right server . And when the service restarts ,duboo There's automatic discovery of services , Consumers don't need to restart to access new services .

2.4.2 problem 2: If ZK The cluster is down for a short time , Whether user access is limited ?

answer : User access is not affected , Because consumers store service list information locally , When accessing a faulty machine , Automatically change the logo information to down attribute .

2.5 Dubbo Load balancing strategy

2.5.1 Types of load balancing

1. Client load balancing
Dubbo/SpringCloud Wait for microservice framework
 Insert picture description here

2. Server side load balancing
explain : After the client initiates the request , Load balancing must be done by a unified server , All the pressure is in the server .
NGINX
 Insert picture description here

2.5.2 Dubbo Load balancing mode

`@RestController
public class UserController {
// utilize dubbo To create a proxy object for the interface utilize rpc call
//@Reference(loadbalance = "random") // The default policy Load balancing random strategy
//@Reference(loadbalance = "roundrobin") // Polling mode
//@Reference(loadbalance = "consistenthash") // Uniformity hash Consumer binding server provider
@Reference(loadbalance = "leastactive") // Select the server with small load to access
private UserService userService;
}`

3 Jingtao project Dubbo reform

3.1 reform JT-SSO

3.1.1 add to jar Package file

 `<!-- introduce dubbo To configure -->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>0.2.0</version>
</dependency>`

3.1.2 establish DubboUserService Interface

 Insert picture description here

3.1.3 Create a provider implementation class

 Insert picture description here

3.1.3 Editor provider YML The configuration file

`server:
port: 8093
servlet:
context-path: /
spring:
datasource:
# introduce druid data source
#type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/jtdb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
username: root
password: root
mvc:
view:
prefix: /WEB-INF/views/
suffix: .jsp
#mybatis-plush To configure
mybatis-plus:
type-aliases-package: com.jt.pojo
mapper-locations: classpath:/mybatis/mappers/*.xml
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.jt.mapper: debug
# About Dubbo To configure
dubbo:
scan:
basePackages: com.jt # Appoint dubbo The package path of scanning dubbo annotation
application: # apply name
name: provider-user # An interface corresponds to a service name An interface can have multiple implementations
registry: # Registry Center The user gets the data from the machine The host is only responsible for monitoring the entire cluster Data synchronization
address: zookeeper://192.168.126.129:2181?backup=192.168.126.129:2182,192.168.126.129:2183
protocol: # Designated agreement
name: dubbo # Use dubbo agreement (tcp-ip) web-controller Call directly sso-Service
port: 20880 # Each service has its own specific port Can't repeat .`

3.1.4 Start the service provider

test Dubbo Whether the server starts normally .
 Insert picture description here

3.2 Transforming service consumers JT-WEB

3.2.1 Inject Service Interface

 Insert picture description here

3.2.2 Edit consumer profile

`server:
port: 8092
spring: # Definition springmvc view resolver
mvc:
view:
prefix: /WEB-INF/views/
suffix: .jsp
dubbo:
scan:
basePackages: com.jt
application:
name: consumer-web # Define the consumer name
registry: # Address of Registration Center
address: zookeeper://192.168.126.129:2181?backup=192.168.126.129:2182,192.168.126.129:2183`

3.2.3 Start the effect test

 Insert picture description here

4. User module implementation

4.1 User registration

4.1.1 URL analysis

according to url Address description request is a same domain request .
 Insert picture description here
parameter information :
 Insert picture description here

4.1.2 page JS analysis

explain : According to the analysis, the returned value data information should be SysResult object
 Insert picture description here

4.1.3 edit UserController

 `/**
* demand : Realize user information registration
* 1.url Request address : http://www.jt.com/user/doRegister
* 2. Request parameters : {password:_password,username:_username,phone:_phone},
* 3. Return value result : SysResult object
*/
@RequestMapping("/doRegister")
@ResponseBody // Translate data into JSON
public SysResult saveUser(User user){
// Consumers give dubbo The agreement will user Object for remote network data transmission .
userService.saveUser(user);
return SysResult.success();
}`

4.1.4 edit UserService

`/**
* matters needing attention :
* 1. Temporarily use a phone number instead of a mailbox
* 2. The password goes on md5 encryption .
* 3. Attention should be paid to transaction control in warehousing operation
* @param user
*/
@Override
public void saveUser(User user) {
String md5Pass =
DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
user.setEmail(user.getPhone())
.setPassword(md5Pass);
userMapper.insert(user);
}`

4.1.5 Page effect display

 Insert picture description here

4.2 About ZK Data storage structure

explain : stay zk The storage of data in the A tree structure The way to keep
command : [root@localhost bin]# sh zkCli.sh
Query command : ls /… Insert picture description here

4.3 Introduction to the principle of single sign on

4.3.1 There are some problems with traditional login

explain : If the SESSION To achieve the user login operation , because nginx Load balancing strategy , Users can access different servers . however Session Cannot share , So users log in frequently . The user experience is not good .
 Insert picture description here

4.3.2 SSO

Single sign on (SingleSignOn,SSO), Is through the user's one-time authentication login . When the user logs in on the authentication server once , You can get access to other associated systems and applications in the single sign on system , At the same time, this implementation does not need the administrator to modify the user's login status or other information , This means that in multiple applications , Users only need to log in once to access all the mutual trust application systems . This method reduces the time consumption caused by login , Assisted user management , It's popular at present [1]

4.3.3 Jingtao project single sign on Design

 Insert picture description here
Implementation steps :
1. When a user enters a user name and password and clicks login , Send the request to JT-WEB Consumer servers .
2.JT-WEB The server transmits user information to JT-SSO Single sign on system completes data verification .
3. If login is successful , The key information is generated dynamically , take user Data into json. Save to redis in . Pay attention to the time-out setting .
4.JT-SSO The credentials that will be logged in Pass to JT-WEB The server .
5.JT-WEB The server sends the user key TICKET Information is saved to the user's cookie in Pay attention to the timeout setting .
6. If login is unsuccessful , The error message can be returned directly .

4.4 User single sign on Implementation

4.4.1 page url analysis

 Insert picture description here

4.4.2 Page parameter analysis

 Insert picture description here

4.4.3 page JS analysis

 Insert picture description here

4.4.4 edit UserController

 `/**
* Complete the user login operation
* 1.url Address : http://www.jt.com/user/doLogin?r=0.9309436837648131
* 2. Parameters : {username:_username,password:_password},
* 3. Return value result : SysResult object
*
* 4.Cookie:
* 4.1 setPath("/") path If you need to get cookie Data in , be url Set the path where the address is located .
* url:http://www.jt.com/person/findAll
* cookie.setPath("/"); It's usually /
* cookie.setPath("/person");
* 4.2 setDomain("xxxxx") Set up cookie Shared domain name address .
*/
@RequestMapping("/doLogin")
@ResponseBody
public SysResult doLogin(User user, HttpServletResponse response){
String ticket = userService.doLogin(user);
if(StringUtils.isEmpty(ticket)){
// User name or password error
return SysResult.fail();
}else{
//1. establish Cookie
Cookie cookie = new Cookie("JT_TICKET",ticket);
cookie.setMaxAge(7*24*60*60); // Set up cookie Survival period
cookie.setPath("/"); // Set up cookie Effective range
cookie.setDomain("jt.com"); // Set up cookie Shared domain name It's a must for single sign on
response.addCookie(cookie);
return SysResult.success(); // Indicates that the user has successfully logged in !!
}
}`

4.4.5 edit UserService

`/**
* 1. Get user information and verify whether there are records in the database
* 2. Yes Start the single sign on process
* 3. No, Go straight back to null that will do
* @param user
* @return
*/
@Override
public String doLogin(User user) { //username/password
//1. Encrypt plaintext
String md5Pass =
DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
user.setPassword(md5Pass);
QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
// According to the object is not null The properties of are as follows where Conditions .
User userDB = userMapper.selectOne(queryWrapper);
if(userDB == null){
// Wrong user name or password
return null;
}else{ // The user name and password are correct Realize single sign on operation
String ticket = UUID.randomUUID().toString();
// If you save the data to a third party Desensitization is usually required
userDB.setPassword("123456 Do you believe it? ??");
String userJSON = ObjectMapperUtil.toJSON(userDB);
jedisCluster.setex(ticket, 7*24*60*60, userJSON);
return ticket;
}
}`

4.4.5 Page effect display

 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课程百度云