- 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 .
1.2 Dubbo characteristic
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 .
2.2 Introduction to service providers
2.2.1 Provider code structure
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
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
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
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
3.1.3 Create a provider implementation class
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 .
3.2 Transforming service consumers JT-WEB
3.2.1 Inject Service Interface
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
4. User module implementation
4.1 User registration
4.1.1 URL analysis
according to url Address description request is a same domain request .
parameter information :
4.1.2 page JS analysis
explain : According to the analysis, the returned value data information should be SysResult object
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
4.2 About ZK Data storage structure
explain : stay zk The storage of data in the A tree structure The way to keep
command : [[email protected] bin]# sh zkCli.sh
Query command : ls /…
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 .
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
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
4.4.2 Page parameter analysis
4.4.3 page JS analysis
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;
}
}`