cgb2007 Jingtao day18

  1. Dubbo
    1.1 creating interfaces
    1). Define interface

    2). Define interface code

    1.2 creating service producers
    1.2.1 define the producer's 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)	//rpc is implemented within the 3-second timeout
//@org.springframework.stereotype.Service / / give the object to the spring container for 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);
	}
}

1.2.2 provider profile

server:
  port: 9000   #Define port

spring:
  datasource:
    #Introducing 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 configuration   
dubbo:
  scan:
    basePackages: com.jt    #Specify the package path of dubbo
  application:              #apply name
    name: provider-user     #An interface corresponds to a service name
  registry:
    address: zookeeper://192.168.126.129:2181?backup=192.168.126.129:2182,192.168.126.129:2183
  protocol:  #Specified agreement
    name: dubbo  #Using dubbo protocol (TCP IP) web controller to call SSO service directly
    port: 20880  #Each service has its own specific port and cannot be repeated

      
mybatis-plus:
  type-aliases-package: com.jt.dubbo.pojo       #Configure alias package path
  mapper-locations: classpath:/mybatis/mappers/*.xml  #Add mapper mapping file
  configuration:
    map-underscore-to-camel-case: true                #Turn on hump mapping rules

1.3 service consumers
1.3.1 editing 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 {
	
	//Use dubbo to create proxy objects for the interface, and use rpc to call
	//Calling a remote service is as simple as calling your own service!!!
	@Reference
	private UserService userService; 
	
	/**
	 * Dubbo Characteristics of framework call: remote RPC call is as simple as calling its own local service
	 * @return
	 */
	@RequestMapping("/findAll")
	public List<User> findAll(){
		
		//The object data passed during remote call must be serialized
		return userService.findAll();
	}
	
	@RequestMapping("/saveUser/{name}/{age}/{sex}")
	public String saveUser(User user) {
		
		userService.saveUser(user);
		return "User warehousing succeeded!!!";
	}
}

1.3.2 edit YML configuration file

server:
  port: 9001
dubbo:
  scan:
    basePackages: com.jt
  application:
    name: consumer-user   #Define 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

1.3.3 consumer testing

1.4 Dubbo high availability test
1.4.1 test requirements
1). Test whether user access is affected when the server is down User access is not affected zk heartbeat detection mechanism
2). Test whether user access is affected when zk cluster goes down Unaffected consumers have local service list data and maintain it by themselves
3). Test whether there is load balancing effect. User access has load balancing effect

1.5 Dubbo load balancing
1.5.1 load balancing mode
1. Server load balancing (centralized load balancing)
Note: users do not know who the real server is when accessing the server, which is dynamically managed by the load balancing server
Typical representative: NGINX
Generally, nginx server is used as reverse proxy, and load balancing is only the function provided

2. Client load balancing
Note: when using the microservice architecture, when consumers access the service provider, the load balancing mechanism has been completed when consumers access the provider because the load balancing strategy has been implemented within the framework So all the pressure is balanced among consumers


1.5.2 load balancing - random algorithm
The default condition is random algorithm


1.5.2 load balancing - polling algorithm


1.5.3 load balancing consistency hash


1.5.3 load balancing - minimum access


2. Reconstruction of Beijing Taobao project
2.0 import jar package

    <dependency>
        <groupId>com.alibaba.boot</groupId>
        <artifactId>dubbo-spring-boot-starter</artifactId>
        <version>0.2.0</version>
    </dependency>

2.1 reconfiguration interface project
Description: add interface file in JT common

2.2 reconstruction jt-sso (producer)
2.2.1 edit Service implementation class

2.2.2 edit YML configuration file

server:
  port: 8093
  servlet:
    context-path: /    #Publish default values in the root directory
spring:
  datasource:
    #Introducing 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

  mvc:
    view:
      prefix: /WEB-INF/views/
      suffix: .jsp
#Mybatis plug configuration
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 configuration
dubbo:
  scan:
    basePackages: com.jt    #Specify the package path of dubbo
  application:              #apply name
    name: provider-user     #An interface corresponds to a service name
  registry:
    address: zookeeper://192.168.126.129:2181?backup=192.168.126.129:2182,192.168.126.129:2183
  protocol:  #Specified agreement
    name: dubbo  #Using dubbo protocol (TCP IP) web controller to call SSO service directly
    port: 20880  #Each service has its own specific port and cannot be repeated

Reconstruction of consumer services
2.3.1 editing UserController

2.3.2 edit YML configuration file

server:
  port: 8092    
spring:     #Define spring MVC view parser
  mvc:
    view:
      prefix: /WEB-INF/views/
      suffix: .jsp
      
#Configure dubbo consumer
dubbo:
  scan:
    basePackages: com.jt
  application:
    name: consumer-user   #Define 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
  1. User module implementation
    3.1 user registration implementation
    3.1.1 page analysis
    1). Page url address

2. Page submission parameters

3. Page JS analysis

3.1.2 editing UserController

 /**
     * Complete user registration
     * url Address: http://www.jt.com/user/doRegister
     *          Request Method: POST
     * Request parameters:
     *          password: admin123
     *          username: admin123123123
     *          phone: 13111112225
     * Return value type:
     *          SysResult object
     */
    @RequestMapping("/doRegister")
    @ResponseBody
    public SysResult saveUser(User user){

        //RPC call using dubbo
        dubboUserService.saveUser(user);
        return SysResult.success();
    }

3.1.2 editing UserService

package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

@Service(timeout = 3000)
public class DubboUserServiceImpl implements DubboUserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public void saveUser(User user) {
        //The password is encrypted in md5 mode
        String password = user.getPassword();
        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setEmail(user.getPhone()).setPassword(md5Pass);
        userMapper.insert(user);
    }
}

3.1.3 page effect display

3.2 user login
3.2.1 implementation of single sign on Service
Single sign on (SSO) is a one-time authentication login of users. When a user logs in on the identity authentication server once, he can gain access to other associated systems and application software in the single sign on system. At the same time, this implementation does not require the administrator to modify the user's login status or other information, which means that in multiple application systems, users can access all mutually trusted application systems with only one login. This method reduces the time consumption caused by login and assists user management


Implementation steps:
1. After entering the user name and password, click the login button to start the login operation
2.JT-WEB sends a request to JT-SSO to complete data verification
3. After JT-SSO obtains the data information, the user verification is completed. If the verification passes, the user information is transformed into json And dynamically generate UUID Save the data to redis And return the value UUID
If the verification does not exist, you can directly return to "does not exist"
4.JT-SSO returns data to JT-WEB server
5. If the login is successful, save the user UUID to the cookie of the client

3.2.2 page URL analysis
1).url request

2).url parameter

3). Page JS analysis

3.2.3 editing UserController

 /**
     * Business: complete user login operation
     * url Address: http://www.jt.com/user/doLogin?r=0.35842191622936337
     * Parameters:
     *          username: admin123
     *          password: admin123456
     * Return value: SysResult object
     *
     * Specific business realization:
     *      1.Verify that the user name and password are correct
     *      2.Judge whether the returned value result is null. If the user name and password are wrong, return 201 status code
     *      3.If the returned value is not null, UUID can be saved in the cookie
     *
     *  Cookie Knowledge introduction:
     *      1.cookie.setPath("/")  The root directory is valid
     *      url1:  www.jt.com/addUser
     *      url2:  www.jt.com/user/addUser
     *
     *      2. cookie.setDomain("Domain name (address "); in which domain are cookie s shared
     *      Example 1: cookie setDomain("www.jt.com");
     *               Only at www.jt.com COM domain name is valid
     *
     *               cookie.setDomain("jt.com");
     *               Only in JT The domain name at the end of COM is valid
     *
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public SysResult doLogin(User user, HttpServletResponse response){
        String uuid = dubboUserService.doLogin(user);
        if(StringUtils.isEmpty(uuid)){
            return SysResult.fail();
        }
        //Save uuid to Cookie
        Cookie cookie = new Cookie("JT_TICKET",uuid);
        cookie.setMaxAge(30*24*60*60);  //Keep cookies valid for 30 days
        cookie.setPath("/");            //At which url path does the cookie take effect
        cookie.setDomain("jt.com");     //Set cookie sharing
        response.addCookie(cookie);

        return SysResult.success();
    }

3.2.4 editing UserService

  /**
     * 1.Query backend server data according to user name and password
     *   Encrypt the password
     * @param user
     * @return
     */
    @Override
    public String doLogin(User user) {
        String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);//u/p cannot
        //Act as the where condition according to the non empty attribute in the object
        User userDB = userMapper.selectOne(queryWrapper);
        if(userDB == null){
            //Error according to user name and password
            return null;
        }
        //Start single sign on business operation
        String uuid = UUID.randomUUID()
                          .toString()
                          .replace("-", "");
        userDB.setPassword("123456 Do you believe it?");   //Remove valid information
        String userJSON = ObjectMapperUtil.toJSON(userDB);
        jedisCluster.setex(uuid, 30*24*60*60, userJSON);

        return uuid;
    }

3.2.5 page effect display

3.3 user information echo
3.3.1 user information echo business requirements
Idea: users dynamically obtain remote server data information through TICKET information and JSONP Then return the data and echo the data

3.3.2 user URL request

3.3.3 page JS analysis

3.3.4 edit the UserController of JT-SSO

 /**
     * Business description:
     *   Get the user's JSON data through cross domain request
     *   1.url Address: http://sso.jt.com/user/query/efd321aec0ca4cd6a319b49bd0bed2db?callback=jsonp1605775149414&_=1605775149460
     *   2.Request parameter: ticket information
     *   3.Return value: SysResult object (userJSON)
     *   Requirement: get user JSON string through ticket information
     */
    @RequestMapping("/query/{ticket}")
    public JSONPObject findUserByTicket(@PathVariable String ticket,String callback){

        String userJSON = jedisCluster.get(ticket);
        if(StringUtils.isEmpty(userJSON)){

            return new JSONPObject(callback, SysResult.fail());
        }else{
            return new JSONPObject(callback, SysResult.success(userJSON));
        }
    }

3.3.5 page effect display

3.4 user login operation
3.4.1 exit business logic
When the user clicks to exit the operation, it should be redirected to the system home page Delete redis information / Cookie information at the same time

3.4.2 editing UserController

 /**
     * User exit operation completed
     * url Address: http://www.jt.com/user/logout.html
     * Parameter: no parameter
     * Return value: String redirect to the system home page
     * Business:
     *      1.Delete redis K-V to get ticket information
     *      2.delete cookie 
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response){
        //1. Get JT in Cookie_ Tick value
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length>0){
            for (Cookie cookie : cookies){
                if(cookie.getName().equals("JT_TICKET")){
                    String ticket = cookie.getValue();
                    //redis deletes ticket information
                    jedisCluster.del(ticket);
                    cookie.setMaxAge(0);    //0 means delete now
                    //Rule cookie s must be strictly defined if they need to be operated
                    cookie.setPath("/");
                    cookie.setDomain("jt.com");
                    response.addCookie(cookie);
                }
            }
        }

        return "redirect:/";
    }
  1. Commodity information display
    4.1 description of business requirements
    When the user clicks on the product, he should jump to the product display page, where two parts of data should be displayed Itemdata / itemDesc data item.jsp page
    Data value method:
    1. Get item information ${item.title}
    2. Get ItemDesc data ${itemDesc.itemDesc}

4.2 reconstruction of jt-management
4.2.1 edit ItemService

4.2.2 edit YML configuration

server:
  port: 8091
  servlet:
    context-path: /    #Publish default values in the root directory
spring:
  datasource:
    #Introducing 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

  mvc:
    view:
      prefix: /WEB-INF/views/
      suffix: .jsp
#Mybatis plug configuration
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

#Configure manage Dubbo service
dubbo:
  scan:
    basePackages: com.jt    #Specify the package path of dubbo
  application:              #apply name
    name: provider-item     #An interface corresponds to a service name
  registry:
    address: zookeeper://192.168.126.129:2181?backup=192.168.126.129:2182,192.168.126.129:2183
  protocol:  #Specified agreement
    name: dubbo  #Using dubbo protocol (TCP IP) web controller to call SSO service directly
    port: 20881  #Each service has its own specific port and cannot be repeated

4.3 realize page Jump
4.3.1 page URL analysis

4.3.2 editing ItemController

package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.service.DubboItemService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.xml.ws.RequestWrapper;

@Controller
public class ItemController {

    @Reference(check = false)
    private DubboItemService itemService;

    /**
     * Realize the display of goods
     * url:     http://www.jt.com/items/562379.html
     * Parameter: 562379 commodity ID No
     * Return value: item jsp
     * Page value: item object / itemDesc object
     *          {item.id/title}
     */
    @RequestMapping("/items/{itemId}")
    public String findItemById(@PathVariable Long itemId, Model model){

        Item item = itemService.findItemById(itemId);
        ItemDesc itemDesc = itemService.findItemDescById(itemId);
        model.addAttribute("item",item);
        model.addAttribute("itemDesc",itemDesc);
        return "item";
    }

}

4.3.3 edit ItemService

package com.jt.web.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.service.DubboItemService;
import org.springframework.beans.factory.annotation.Autowired;

@Service(timeout = 3000)
public class DubboItemServiceImpl implements DubboItemService {

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;


    @Override
    public Item findItemById(Long itemId) {

        return itemMapper.selectById(itemId);
    }

    @Override
    public ItemDesc findItemDescById(Long itemId) {

        return itemDescMapper.selectById(itemId);
    }
}

4.3.4 page effect display

5 shopping cart operation
5.1 business analysis
Note: when users click the shopping cart button, they should jump to the shopping cart list page

Page name: cart jsp
Page data: ${cartList}

5.2 create shopping Cart POJO

package com.jt.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.experimental.Accessors;

@TableName("tb_cart")
@Data
@Accessors(chain = true)
public class Cart extends BasePojo{
   @TableId(type = IdType.AUTO)     //Primary key auto increment
   private Long id; //Shopping cart Id number
   private Long userId; //User Id number
   private Long itemId; //Item id number
   private String itemTitle;    //Product title
   private String itemImage;    //Product picture information
   private Long itemPrice;
   private Integer num;
}

5.3 create JT-CART project
5.3.1 create project

5.3.2 add inheritance dependent plug-ins

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>jt-cart</artifactId>


    <parent>
        <artifactId>jt2007</artifactId>
        <groupId>com.jt</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <!--3.Dependent tools API-->
    <dependencies>
        <dependency>
            <groupId>com.jt</groupId>
            <artifactId>jt-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <!--4.add to maven plug-in unit-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

5.3.3 shopping cart project structure

Tags: Java

Posted by lovesmith on Wed, 04 May 2022 02:13:26 +0300