2.18日学习打卡----初学Dubbo(三)

2.18日学习打卡

目录:

  • 2.18日学习打卡
  • Dubbo实战
    • 项目介绍
    • 创建dubbo_parent父项目
    • 创建子项目user_api项目
    • 创建子项目user_consumer项目
    • 创建子项目user_provider项目模块
    • 用户实体类构建
    • 创建添加用户接口
    • 查询用户业务接口
    • 更新用户业务接口
    • 删除用户业务接口
    • 集成Thymeleaf
    • 用户添加业务消费者实现
    • 用户查询业务消费者实现
    • 在Consumer中调用更新用户业务
    • 用户删除业务消费者实现

Dubbo实战

项目介绍

需求

完成用户表的CRUD操作。

技术架构
2.18日学习打卡----初学Dubbo(三)_第1张图片
项目结构设计

本项目采用maven分模块开发方式,即对整个项目拆分为几个maven工程,每个maven工程存放特定的一类代码。

2.18日学习打卡----初学Dubbo(三)_第2张图片

解释:

  • user_api:公共接口
  • user_consumer:服务消费者
  • user_provider:服务生产者

创建dubbo_parent父项目

修改pom文件


<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.0modelVersion>

    <groupId>com.jjygroupId>
    <artifactId>dubbo-parentartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>pompackaging>

    <properties>
        <dubbo.spring.starter.version>2.7.6dubbo.spring.starter.version>
        <dubbo.registry.zookeeper.version>2.7.6dubbo.registry.zookeeper.version>
        <mybatisplus.spring.starter.version>3.5.0mybatisplus.spring.starter.version>
        <mysql.connector.version>5.1.49mysql.connector.version>
    properties>

    <dependencyManagement>
        <dependencies>
            
            <dependency>
                <groupId>org.apache.dubbogroupId>
                <artifactId>dubbo-spring-boot-starterartifactId>
                <version>${dubbo.spring.starter.version}version>
            dependency>
            
            <dependency>
                <groupId>org.apache.dubbogroupId>
                <artifactId>dubbo-registry-zookeeperartifactId>
                <version>${dubbo.registry.zookeeper.version}version>
            dependency>
            
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-boot-starterartifactId>
                <version>${mybatisplus.spring.starter.version}version>
            dependency>
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>${mysql.connector.version}version>
            dependency>
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <version>1.18.22version>
            dependency>
        dependencies>

    dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                configuration>
            plugin>
        plugins>
    build>
project>

注意
pom.xml文件里添加的依赖出现红色字样的解决方法就是把这个标签先删除掉,等maven从中央仓库把依赖拉到本地后再恢复此标签即可。

创建子项目user_api项目

2.18日学习打卡----初学Dubbo(三)_第3张图片

修改pom文件


<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.0modelVersion>
    <parent>
        <groupId>com.jjygroupId>
        <artifactId>dubbo-parentartifactId>
        <version>1.0-SNAPSHOTversion>
    parent>

    <artifactId>user_apiartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>
    <dependencies>
    <dependency>
        <groupId>org.apache.dubbogroupId>
        <artifactId>dubbo-registry-zookeeperartifactId>
        <exclusions>
            <exclusion>
                <artifactId>slf4j-log4j12artifactId>
                <groupId>org.slf4jgroupId>
            exclusion>
        exclusions>
    dependency>
    
    <dependency>
        <groupId>org.apache.dubbogroupId>
        <artifactId>dubbo-spring-boot-starterartifactId>
    dependency>
    dependencies>
project>

创建子项目user_consumer项目

创建SpringBoot项目
添加lombok和springweb
修改pom


<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <groupId>com.jjygroupId>
    <artifactId>user_consumerartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>user_consumername>
    <description>user_consumerdescription>
    <properties>
        <java.version>1.8java.version>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <spring-boot.version>2.6.13spring-boot.version>
    properties>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-dependenciesartifactId>
                <version>${spring-boot.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
            <dependency>
                <groupId>com.jjygroupId>
                <artifactId>dubbo-parentartifactId>
                <version>1.0-SNAPSHOTversion>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.8.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.version}version>
                <configuration>
                    <mainClass>com.jjy.UserConsumerApplicationmainClass>
                    <skip>trueskip>
                configuration>
                <executions>
                    <execution>
                        <id>repackageid>
                        <goals>
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

创建子项目user_provider项目模块

2.18日学习打卡----初学Dubbo(三)_第4张图片
创建maven项目 命名user_provider
修改pom
2.18日学习打卡----初学Dubbo(三)_第5张图片
创建pojo,mapper,provider工程
以user_provider为父项目构建

目录结构如下
2.18日学习打卡----初学Dubbo(三)_第6张图片

用户实体类构建

2.18日学习打卡----初学Dubbo(三)_第7张图片
Docker构建Mysql数据库

docker run -d --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql:8.0

进入数据库

docker exec -it mysql /bin/bash
mysql -uroot -p123456

创建数据库

create database test;
use test

创建用户表

CREATE TABLE user
(
   id BIGINT(20) NOT NULL COMMENT '主键ID',
   name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
   age INT(11) NULL DEFAULT NULL COMMENT '年龄',
  PRIMARY KEY (id)
);

创建用户实体类(在pojo工程创建)

@Data
public class User implements Serializable {


  // 用户id
  private Long id;
  // 用户名字
  private String name;
  // 用户年纪
  private Integer age;

}

mapper工程引入pojo工程

  <dependencies>
    <dependency>
      <groupId>com.itbaizhangroupId>
      <artifactId>pojoartifactId>
      <version>1.0-SNAPSHOTversion>
    dependency>
  dependencies>

配置Mybaits-plus
修改mapper工程的pom


<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.0modelVersion>
    <parent>
        <groupId>com.jjygroupId>
        <artifactId>user_providerartifactId>
        <version>1.0-SNAPSHOTversion>
    parent>

    <artifactId>mapperartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>
    <dependencies>
        <dependency>
            <groupId>com.jjygroupId>
            <artifactId>pojoartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
    dependencies>

project>

在mapper工程建立UserMapper接口
2.18日学习打卡----初学Dubbo(三)_第8张图片
userMapper

package com.jjy.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jjy.pojo.User;

/**
 * 用户持久层
 *
 */
public interface UserMapper extends BaseMapper<User> {


}

修改provider的POM文件

引入Mapper依赖
pom 文件为


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.6.13version>
        <relativePath>relativePath>
    parent>

    <artifactId>providerartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>
    <dependencies>
        <dependency>
        <groupId>com.jjygroupId>
        <artifactId>mapperartifactId>
        <version>1.0-SNAPSHOTversion>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>
    dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.jjygroupId>
                <artifactId>user_providerartifactId>
                <version>1.0-SNAPSHOTversion>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>


project>

2.18日学习打卡----初学Dubbo(三)_第9张图片
手动创建ProviderApplication和application.properties
ProviderApplication

package com.jjy;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@Slf4j
@SpringBootApplication
@MapperScan("com.jjy.mapper")
public class ProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class,args);
    }
}

application.properties

################ 配置MySQL数据源 ##############
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.66.100:3307/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

创建添加用户接口

在user_api工程引入pojo工程

 <dependency>
            <groupId>com.jjygroupId>
            <artifactId>pojoartifactId>
            <version>1.0-SNAPSHOTversion>
 dependency>

在user_api项目中创建添加用户接口

public interface IAddUserService {


  /**
   * 添加用户
   * @param users
   */
  void addUser(User users);


}

引入user_api工程

<dependency>
  <groupId>com.itbaizhangroupId>
  <artifactId>user_apiartifactId>
  <version>1.0-SNAPSHOTversion>
dependency>

添加Dubbo配置

################ Dubbo 配置 ####################
dubbo.application.name=myProvider
# 单机
dubbo.registry.address=zookeeper://192.168.66.100:2181
# zookeeper 集群
#dubbo.registry.address=zookeeper://192.168.233.130:2181?backup=192.168.233.130:2182,192.168.233.130:2183
dubbo.registry.timeout=50000
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
dubbo.scan.base-packages=com.jjy.service

在provider中实现添加用户业务接口

/**
 * 添加用户业务
 */
public class AddUserServiceImpl implements IAddUserService {


  @Autowired
  private UserMapper userMapper;


  @Override
  public int addUser(User users) {
    return userMapper.insert(users);
   }
}

查询用户业务接口

public interface FindUserService {
  List<Users> findUserAll();
}

在 provider中实现查询用户业务接口

/**
 * 查询用户业务层
 */
@Service
public class FindUserServiceImpl implements FindUserService {


  @Autowired
  private UserMapper userMapper;


  /**
   * 查询用户
   * @return
   */
  @Override
  public List<User> findUserAll() {
    return userMapper.selectList(null);
   }


}

更新用户业务接口

在 user_api 项目中添加更新用户业务接口

public interface UpdateUserService {
    User preUpdateUsers(Long userid);
    void updateUsers(User users);
}

在 provider 中实现更新用户业务接口

/**
 * 更新用户业务
 */
@Service
public class UpdateUserServiceImpl implements IUpdateUserService {


   @Autowired
   private UserMapper userMapper;


   /**
   * 根据用户id更新用户名字
   * @param users
   * @return
   */
   @Override
   public Integer updateUsers(User users) {
     return  userMapper.updateById(users);
   }
  
}

删除用户业务接口

public interface DeleteUserService {
  /**
   * 根据用户id删除用户
   * @param userid
   */
  void deleteUsersById(Long userid);
}

在provider中实现删除用户业务接口

@Service
public class DeleteUserServiceImpl implements DeleteUserService {


  @Autowired
  private UserMapper userMapper;


  @Override
  public Integer deleteUsersById(Long userid) {
    return userMapper.deleteById(userid);
   }
}

集成Thymeleaf

修改user_consumer工程pom文件

<dependency>
  <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-thymeleafartifactId>
dependency>

配置视图解析器
默认

spring-boot很多配置都有默认配置,比如默认页面映射路径为

classpath:/templates/*.html 

同样静态文件路径为

classpath:/static/

自定义
在application.properties(或者application.yml)中可以配置thymeleaf模板解析器属性.就像使用springMVC的JSP解析器配置一样

#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html 
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
#thymeleaf end

编写index.html首页

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../resources/favicon.ico"
th:href="@{/static/favicon.ico}"/>
<head>
<meta charset="UTF-8">
<title>首页title>
head>
<body>
<a href="/addUser">添加用户a>   <a
href="/user/getUser">查询用户a>
body>
html>

创建页面跳转 Controller

@Controller
public class PageController {
   /**
   * 完成页面跳转
   */
   @GetMapping("/{page}")
   public String showPage(@PathVariable String page){
     return page;
   }
}

用户添加业务消费者实现

编写adduser.html页面

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../resources/favicon.ico"
      th:href="@{/static/favicon.ico}"/>
<head>
    <meta charset="UTF-8">
    <title>添加用户title>
head>
<body>
<form action="user/addUser" method="post">
    用户姓名:<input type="text" name="name" placeholder="请输入名字"/><br/>
    用户年龄:<input type="text" name="age" placeholder="请输入年龄"/><br/>
    <input type="submit" value="OK"/>
form>
body>
html>


编写用户添加接口

package com.jjy.controller;

import com.jjy.Service.UserService;
import com.jjy.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 处理用户操作控制器
 */
@Controller
@RequestMapping("/user")
public class UsersController {


    @Autowired
    private UserService userService;
    /**
     * 处理添加用户请求
     */
    @RequestMapping("/addUser")
    public String addUser(User users){
        this.userService.adduser(users);
        return "redirect:/ok";
    }


}

编写用户接口

public interface UserService {


  /**
   * 添加用户
   * @param users
   */
  void addUser(User users);


}

编写用户接口实现类

package com.jjy.Service.impl;

import com.jjy.Service.UserService;
import com.jjy.api.AddUserService;
import com.jjy.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
   @Reference
    AddUserService addUserService;
    @Override
    public void adduser(User user) {
        addUserService.addUser(user);
    }
}

编写返回页面ok.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}"/>
<head>
  <meta charset="UTF-8">
  <title>成功页面title>
head>
<body>
   操作成功请<a href="/index">返回a>
body>
html>

用户查询业务消费者实现

修改Consumer添加处理查询用户请求接口

package com.jjy.Service;

import com.jjy.pojo.User;

import java.util.List;

public interface UserService {
    /**
     * 添加用户
     * @param user
     */
    void adduser(User user);
    /**
     * 查询用户
     * @return
     */
    List<User> getUsersAll();
}

编写接口实现类型

package com.jjy.Service.impl;

import com.jjy.Service.UserService;
import com.jjy.api.AddUserService;
import com.jjy.api.FindUserService;
import com.jjy.pojo.User;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
   @Reference
   private AddUserService addUserService;
   @Reference
    FindUserService findUserService;
    @Override
    public void adduser(User user) {
        addUserService.addUser(user);
    }

    @Override
    public List<User> getUsersAll() {
        return findUserService.findUserAll();
    }
}

修改Consumer添加处理查询用户请求



创建showUser 页面

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../resources/favicon.ico"
   th:href="@{/static/favicon.ico}"/>
<head>
  <meta charset="UTF-8">
  <title>显示用户title>
head>
<body>
<table border="1" align="center">
  <tr>
    <th>用户 IDth>
    <th>用户姓名th>
    <th>用户年龄th>
    <th>操作th>
  tr>
  <tr th:each="user:${list}">
    <td th:text="${user.id}">td>
    <td th:text="${user.name}">td>
    <td th:text="${user.age}">td>
    <td>
      <a
          th:href="@{/user/preUpdateUser(userid=${user.id})}">修改用户
      a>
      <a
          th:href="@{/user/deleteUser(userid=${user.id})}">删除用户a>
    td>
  tr>
table>
body>

在Consumer中调用更新用户业务

 /**
     * 根据用户id修改用户名字
     * @param users
     * @return
     */
    void updateUsers(User users);


    /**
     * 根据用户id查询用户信息
     * @param id
     * @return
     */
    User findByUserId(Long id);

编写接口实现类

package com.jjy.Service.impl;

import com.jjy.Service.UserService;
import com.jjy.api.AddUserService;
import com.jjy.api.DeleteUserService;
import com.jjy.api.FindUserService;
import com.jjy.api.UpdateUserService;
import com.jjy.pojo.User;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
   @Reference
   private AddUserService addUserService;
   @Reference
    FindUserService findUserService;
   @Reference
    UpdateUserService updateuserService;
   @Reference
    DeleteUserService deleteUserService;
    @Override
    public void adduser(User user) {
        addUserService.addUser(user);
    }

    @Override
    public List<User> getUsersAll() {
        return findUserService.findUserAll();
    }

    /**
     * 更新用户
     * @param users
     * @return
     */
    @Override
    public void updateUsers(User users) {
        updateuserService.updateUsers(users);
    }

    /**
     * 根据用户id查询用户
     * @param id 用户id
     * @return
     */
    @Override
    public User findByUserId(Long id) {
        return updateuserService.preUpdateUsers(id);
    }
}

修改 Consumer 添加处理查询用户请求



  /**
   * 处理预更新查询请求
   */
@RequestMapping("/preUpdateUser")
public String preUpdateUser(Long userid,Model model){
    User users = this.userService.findByUserId(userid);
    model.addAttribute("users",users);
    return "updateUsers";
 }


/**
* 处理更新用户请求
*/
@PostMapping("/updateUser")
public String updateUser(User users){
  this.userService.updateUsers(users);
  return "redirect:/ok";
}



更新页面updateUser页面

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}"/>
<head>
  <meta charset="UTF-8">
  <title>更新用户title>
head>
<body>
<form action="/user/updateUser" method="post">
  <input type="hidden" name="id" th:value="${users.id}"/><br/>
   用户姓名: <input type="text" name="name" th:value="${users.name}"/><br/>
   用户年龄:<input type="text" name="age" th:value="${users.age}"/><br/>
  <input type="submit" value="Update"/>
form>
body>
html>

用户删除业务消费者实现

修改 Consumer 业务层添加删除用户业务

void deleteUsersById(Long userid);

编写接口实现类

public void deleteUsersById(Long userid) {
    DeleteUserService.deleteUsersById(userid);
}

修改 Consumer 添加处理删除用户请求

/**
* 处理删除用户请求
*/
@RequestMapping("/deleteUser")
public String deleteUser(Long userid){
this.userService.deleteUsersById(userid);
return "redirect:/ok";
}

如果我的内容对你有帮助,请点赞,评论,收藏。创作不易,大家的支持就是我坚持下去的动力!

2.18日学习打卡----初学Dubbo(三)_第10张图片

你可能感兴趣的:(每日学习,学习,dubbo)