热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

SpringBoot08:SpringBoot综合使用MyBatis,Dubbo,Redis

业务背景Student表CREATETABLE`student`(`id`int(11)NOTNULLAUTO_INCREMENT,`name`varchar(255)COLLATEutf8_binDEFAULTNULL,`phon

业务背景

Student表

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_bin DEFAULT NULL,
  `phone` varchar(11) COLLATE utf8_bin DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

两个业务功能

针对上述student表, 综合应用springboot, mybatis, dubbo, redis实现如下两个业务功能

1. 注册学生
  • 要求:

  • 注册接口定义为:int saveStudent(Student student)

  • 利用传入的学生的手机号注册,手机号必须唯一

  • 如果已经存在了手机号, 注册失败, 返回2

  • 如果手机号为空,注册失败,返回-1

  • 注册成功,返回0

2. 查询学生
  • 要求:
  • 查询接口定义为:Student queryStudent(Integer id)
  • 根据id查询目标学生
  • 先到redis查询学生,如果redis没有,从数据库查询
  • 如果数据库有,把查询到的学生放入到redis,返回该学生,后续再次查询这个学生应该从redis就能获取到
  • 如果数据库也没有目标学生,返回空

其他要求

  • 关于Dubbo
    • 要求使用dubbo框架,addStudent, queryStudent是由服务提供者实现的
    • 消费者可以是一个Controller,调用提供者的两个方法, 实现学生的注册和查询
  • 关于前端页面
    • 页面使用html, ajax, jquery
    • 通过postman发送post请求,来注册学生
    • 通过html页面上的form表单,提供文本框输入id, 进行查询
    • html, jquery.js都放到springboot项目的resources/static目录中

编程实现

项目结构

  • 分布式总体项目结构

image

  • 公共接口项目结构

image

  • 服务提供者项目结构

image

  • 消费者项目结构

image

dubbo的公共接口项目

注意该项目为普通的maven项目即可

实体类
package com.example.demo.model;

import java.io.Serializable;

public class Student implements Serializable {
    private static final long serialVersiOnUID= -3272421320600950226L;
    private Integer id;
    private String name;
    private String phone;
    private Integer age;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", phOne='" + phone + '\'' +
                ", age=" + age +
                '}';
    }

    //防止缓存穿透,可以获取默认学生(学生信息故意设置不合法,后期在redis中一眼就能看出来是异常数据),填充到redis中
    public static Student getDefaultStudent(){
        Student student = new Student();
        student.setId(-1);
        student.setName("-");
        student.setPhone("-");
        student.setAge(0);
        return student;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phOne= phone;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Student(Integer id, String name, String phone, Integer age) {
        this.id = id;
        this.name = name;
        this.phOne= phone;
        this.age = age;
    }

    public Student() {
    }
}
提供的服务接口定义
package com.example.demo.service;

import com.example.demo.model.Student;

public interface StudentService {
    //保存学生信息
    int saveStudent(Student student);

    //根据id,查询学生信息
    Student queryStudent(Integer id);
}

dubbo的服务提供者项目

注意:该项目为springboot项目,且在起步依赖里要勾选web(web依赖可以不选), redis, mysql, mybatis的起步依赖

项目配置
  • 额外在pom.xml里手动加入对公共接口项目以及dubbo和zookeeper的依赖
        
        
            com.example.demo
            demo-api
            1.0.0
        

        
        
            org.apache.dubbo
            dubbo-spring-boot-starter
            2.7.8
        


        
        
            org.apache.dubbo
            dubbo-dependencies-zookeeper
            2.7.8
            pom
            
                
                
                    slf4j-log4j12
                    org.slf4j
                
            
        
  • 配置application.properties文件
########################### 配置dubbo
#配置提供的服务名称
dubbo.application.name=student-service-provider

#配置需要扫描的包
dubbo.scan.base-packages=com.example.demo.service

#配置注册中心
dubbo.registry.address=zookeeper://127.0.0.1:2181

########################### 配置redis
#redis服务的ip
spring.redis.host=127.0.0.1

#redis服务的端口
spring.redis.port=6379

########################### mybatis配置
#mybatis中mapper文件编译到的资源路径
mybatis.mapper-locatiOns=classpath:mapper/*.xml

#mybatis日志输出
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

############################ 数据源配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://数据库服务器ip:3306/数据库名?useUnicode=true&characterEncoding=UTF-8&serverTimezOne=GMT%2B8
spring.datasource.username=XXX
spring.datasource.password=YYY
dao层
  • dao接口
package com.example.demo.dao;

import com.example.demo.model.Student;
import org.apache.ibatis.annotations.Param;

public interface StudentDao {
    //以手机号作为查询条件,判断学生是否存在
    Student queryStudentByPhone(@Param("phone") String phone);

    //保存新创建的学生信息
    int saveStudent(Student student);

    //根据学生id,查询学生信息
    Student queryStudentById(@Param("id") Integer id);
}
  • dao接口对应的xml文件, 位于resources/mapper目录下,这里将dao接口和dao.xml文件分开管理



    
    

    
    
        insert into student(name, age, phone) values(#{name}, #{age}, #{phone})
    

    
    


  • 实现公共接口工程里对外提供的服务
package com.example.demo.service.impl;

import com.example.demo.dao.StudentDao;
import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;

@DubboService(interfaceClass = StudentService.class, version = "1.0.0", timeout = 5000)
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentDao studentDao;

    @Resource
    private RedisTemplate redisTemplate;

    //保存新创建的学生
    @Override
    public int saveStudent(Student student) {
        int saveResult = 0;//表示保存学生信息的结果:1/添加成功 -1:手机号为空 2:手机号码重复
        if(student.getPhone() == null){
            saveResult = -1;
        }else{
            Student queryStudentResult = studentDao.queryStudentByPhone(student.getPhone());
            if(queryStudentResult != null){
                saveResult = 2;
            }else{
                //该学生尚未存在,保存到数据库中
                saveResult = studentDao.saveStudent(student);
            }
        }
        return saveResult;
    }

    @Override
    public Student queryStudent(Integer id) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Student.class));
        final String STUDENT_USER_KEY = "STUDENT:";
        String key = STUDENT_USER_KEY + id;
        //先尝试从缓存获取:按照key的格式来查
        Student student = (Student) redisTemplate.opsForValue().get(key);
        System.out.println("------- 从redis中查询数据 ----------> : " + student);
        if(student == null){
            //缓存中没有,需要到数据库查询:按照id格式来查询
            student = studentDao.queryStudentById(id);
            System.out.println("------- 从数据库中查询数据 ---------> : " + student);
            if(student != null){
                //数据库中有该数据,存一份数据到redis中:按照key的格式来存
                redisTemplate.opsForValue().set(key, student);
            }else{
                //防止缓存穿透:对既未在缓存又未在数据库中的数据,设置默认值
                redisTemplate.opsForValue().set(key, Student.getDefaultStudent());
            }
        }
        return student;
    }
}
  • springboot主启动类上添加支持dubbo的注解并添加对dao接口扫描的注解
package com.example;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableDubbo
@MapperScan(basePackages = "com.example.demo.dao")
public class StudentserviceProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(StudentserviceProviderApplication.class, args);
    }
}

dubbo消费者项目

该项目为springboot项目,启动项依赖只要勾选web依赖

pom.xml中的额外依赖均与服务提供者相同

项目配置
  • 配置application.properties
#springboot服务的基本配置
server.port=9090
server.servlet.context-path=/demo

#springboot中使用dubbo的配置
#消费者名称
dubbo.application.name=student-service-consumer

#配置需要扫描的包
dubbo.scan.base-packages=com.example.demo.controller

#配置注册中心
dubbo.registry.address=zookeeper://127.0.0.1:2181
  • 同样在springboot的启动类上添加支持dubbo的注解
package com.example;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableDubbo
public class StudentConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(StudentConsumerApplication.class, args);
    }
}
controller层
  • 消费者与前端交互的controller层, 采用RESTful接口风格
package com.example.demo.controller;

import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StudentController {

    @DubboReference(interfaceClass = StudentService.class, version = "1.0.0")
    private StudentService studentService;

    @PostMapping("/student/add")
    public String addStudent(Student student){
        int saveStudentResult = studentService.saveStudent(student);
        String msg = "";
        if(saveStudentResult == 1){
            msg = "添加学生: " + student.getName() + " 成功";
        }else if(saveStudentResult == -1){
            msg = "手机号不能为空";
        }else if(saveStudentResult == 2){
            msg = "手机号: " + student.getPhone() + " 重复,请更换手机号后重试";
        }
        return msg;
    }

    @PostMapping("/student/query")
    public String queryStudent(Integer id){
        String msg = "";
        Student student = null;
        if(id != null && id > 0){
            student = studentService.queryStudent(id);
            if(student != null){
                msg = "查询到的学生信息: " + student.toString();
            }else{
                msg = "未查询到相关信息";
            }
        }else{
            msg = "输入的id范围不正确";
        }
        return msg;
    }
}
前端页面

前端html页面和js文件位于resources/static目录下

  • 可以借助postman便捷的发送post请求来添加学生

  • 查询学生的请求可以借助如下query.html页面,通过ajax来发送查询请求




    
    
    
    




推荐阅读
  • 实体映射最强工具类:MapStruct真香 ... [详细]
  • 深入理解 SQL 视图、存储过程与事务
    本文详细介绍了SQL中的视图、存储过程和事务的概念及应用。视图为用户提供了一种灵活的数据查询方式,存储过程则封装了复杂的SQL逻辑,而事务确保了数据库操作的完整性和一致性。 ... [详细]
  • 利用存储过程构建年度日历表的详细指南
    本文将介绍如何使用SQL存储过程创建一个完整的年度日历表。通过实例演示,帮助读者掌握存储过程的应用技巧,并提供详细的代码解析和执行步骤。 ... [详细]
  • 图数据库中的知识表示与推理机制
    本文探讨了图数据库及其技术生态系统在知识表示和推理问题上的应用。通过理解图数据结构,尤其是属性图的特性,可以为复杂的数据关系提供高效且优雅的解决方案。我们将详细介绍属性图的基本概念、对象建模、概念建模以及自动推理的过程,并结合实际代码示例进行说明。 ... [详细]
  • 深入解析 Apache Shiro 安全框架架构
    本文详细介绍了 Apache Shiro,一个强大且灵活的开源安全框架。Shiro 专注于简化身份验证、授权、会话管理和加密等复杂的安全操作,使开发者能够更轻松地保护应用程序。其核心目标是提供易于使用和理解的API,同时确保高度的安全性和灵活性。 ... [详细]
  • 探讨如何真正掌握Java EE,包括所需技能、工具和实践经验。资深软件教学总监李刚分享了对毕业生简历中常见问题的看法,并提供了详尽的标准。 ... [详细]
  • 深入理解Redis的数据结构与对象系统
    本文详细探讨了Redis中的数据结构和对象系统的实现,包括字符串、列表、集合、哈希表和有序集合等五种核心对象类型,以及它们所使用的底层数据结构。通过分析源码和相关文献,帮助读者更好地理解Redis的设计原理。 ... [详细]
  • 本文探讨了如何在日常工作中通过优化效率和深入研究核心技术,将技术和知识转化为实际收益。文章结合个人经验,分享了提高工作效率、掌握高价值技能以及选择合适工作环境的方法,帮助读者更好地实现技术变现。 ... [详细]
  • 深入解析Redis内存对象模型
    本文详细介绍了Redis内存对象模型的关键知识点,包括内存统计、内存分配、数据存储细节及优化策略。通过实际案例和专业分析,帮助读者全面理解Redis内存管理机制。 ... [详细]
  • 本文作者分享了在阿里巴巴获得实习offer的经历,包括五轮面试的详细内容和经验总结。其中四轮为技术面试,一轮为HR面试,涵盖了大量的Java技术和项目实践经验。 ... [详细]
  • 本文将介绍由密歇根大学Charles Severance教授主讲的顶级Python入门系列课程,该课程广受好评,被誉为Python学习的最佳选择。通过生动有趣的教学方式,帮助初学者轻松掌握编程基础。 ... [详细]
  • 本文详细介绍了如何通过多种编程语言(如PHP、JSP)实现网站与MySQL数据库的连接,包括创建数据库、表的基本操作,以及数据的读取和写入方法。 ... [详细]
  • 文件描述符、文件句柄与打开文件之间的关联解析
    本文详细探讨了文件描述符、文件句柄和打开文件之间的关系,通过具体示例解释了它们在操作系统中的作用及其相互影响。 ... [详细]
  • Redis Hash 数据结构详解
    本文详细介绍了 Redis 中的 Hash 数据类型及其常用命令。Hash 类型用于存储键值对集合,支持多种操作如插入、查询、更新和删除字段值。此外,文章还探讨了 Hash 类型在实际业务场景中的应用,并提供了优化建议。 ... [详细]
  • 随着Redis功能的不断增强和稳定性提升,其应用范围日益广泛,成为软件开发人员不可或缺的技能之一。本文将深入探讨Redis集群的部署与优化,包括主从备份机制、哨兵模式以及集群功能,帮助读者全面理解并掌握Redis集群的应用。 ... [详细]
author-avatar
ID张蕾
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有