springcloud创建子模块notice-2(手动配置)

上接:springcloud创建子模块notice-1(手动配置)

概述

本文继续配置 mysql、mybatis、dao、service、controller

最终工程结构

如下图:

添加application.yml配置文件

注意:在springboot中推荐使用.yml配置文件,如果不习惯,用.properties配置文件也可以

创建文件

在本工程的 resources 目录下,添加 application.yml 配置文件

注意: 文件所在的路径,千万别搞错了

如下图:

在 弹出窗口输入文件名,如下图:

然后敲回车,创建文件成功,如下图:

成功后,文件图标一般为绿色

配置

server:
  port: 8001  # 配置端口号

spring:
  application:
    name: notice-service   # 服务名称
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: com.mysql.cj.jdbc.Driver              # mysql驱动包
    url: jdbc:mysql://localhost:3306/papernotes?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 1234abcd

# mybatis 整合
mybatis:
  mapperLocations: classpath:mapper/*.xml
  type-aliases-package: top.malaoshi.entities    # 所有Entity别名类所在包

连接mysql 5.7数据库

springboot 2.x 默认使用 MySQL8 的驱动,连接 MySQL5.7,需要加上时区,如下:

url: jdbc:mysql://localhost:3308/scott?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai

关键:&serverTimezone=Asia/Shanghai

实现主启动类

springboot通过类启动

创建类

注意: 类名改为:NoticeMain

编写代码

加上注解,表示springboot启动类,如下:

package org.malaoshi.notice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

数据库

创建表

-- auto-generated definition
create table t_notice
(
    id          varchar(32)  not null
        primary key,
    from_userid varchar(32)  null,
    to_userid   varchar(32)  null,
    msg         varchar(128) null
)
    comment '推送消息日志';

实现操作数据库的类和xml文件

创建实体类

路径:top.malaoshi.notice.entities.Notice

package org.malaoshi.notice.entities;

import java.io.Serializable;

public class Notice implements Serializable {
    /**
     * 主键
     */
    private String id;
    /**
     * 发消息人的id
     */
    private String fromUserid;
    /**
     * 接收消息人的id
     */
    private String toUserid;

    /**
     * 消息
     */
    private String msg;

    public String getId() {
        return id;
    }

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

    public String getFromUserid() {
        return fromUserid;
    }

    public void setFromUserid(String fromUserid) {
        this.fromUserid = fromUserid;
    }

    public String getToUserid() {
        return toUserid;
    }

    public void setToUserid(String toUserid) {
        this.toUserid = toUserid;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

创建dao类(或者Mapper类)

创建Dao为后缀的类(或者Mapper为后缀的类)

路径:top.malaoshi.notice.dao.NoticeDao

package top.malaoshi.notice.dao;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.malaoshi.notice.entities.Notice;

//推荐使用@Mapper,不推荐@Repository
@Mapper
//@Repository
public interface NoticeDao {

    public void create(Notice nl);
    public Notice getNoticeById(String id);
}

实现mapper.xml文件

路径:src/main/resources/mapper/NoticeMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<!-- namespace是dao全路径 -->
<mapper namespace="top.malaoshi.notice.dao.NoticeDao">
    <resultMap id="NoticeMap" type="top.malaoshi.notice.entities.Notice">
        <!-- column 是数据库中的字段 -->
        <!-- property 是类中的属性名 -->
        <!-- jdbcType 是数据库中的类型 -->
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <id column="from_userid" property="fromUserid" jdbcType="VARCHAR"/>
        <id column="to_userid" property="toUserid" jdbcType="VARCHAR"/>
        <id column="msg" property="msg" jdbcType="VARCHAR"/>
    </resultMap>

    <insert id="create" parameterType="top.malaoshi.notice.entities.Notice" >
        insert into t_notice (id,from_userid,to_userid,msg) values (#{id},#{fromUserid},#{toUserid},#{msg})
    </insert>
    <!-- 推荐使用resultMap,更加灵活(不推荐resultType) -->
    <select id="getNoticeById" resultMap="NoticeMap">
        select * from t_notice where id=#{id};
    </select>

</mapper>

创建json封装类

封装类json,将执行成功、失败的信息封装成类,返回给前端json

路径:top.malaoshi.notice.json.CommonResult

package org.malaoshi.notice.json;

import com.fasterxml.jackson.annotation.JsonInclude;

/**
 * json封装类
 * 将执行成功、失败的信息封装成类,返回给前端json
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CommonResult <T>{
    private int code;
    private String msg;
    private T data;

    /**
     * 必须有无参构造方法,反射创建对象时,需要该方法
     */
    public CommonResult() {
    }

    public CommonResult(int code, String msg) {
        this(code,msg,null);
    }

    public CommonResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

实现service

创建service接口

package top.malaoshi.notice.services;

import org.malaoshi.notice.entities.Notice;

import java.util.List;

public interface INoticeService {
    public Notice getNoticeById(String id);

    public void sendNotice(Notice nl);
}

创建service实现类

package top.malaoshi.notice.services.impl;

import top.malaoshi.notice.dao.NoticeDao;
import top.malaoshi.notice.entities.Notice;
import top.malaoshi.notice.services.INoticeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

@Service
public class NoticeServiceImpl implements INoticeService {
    @Resource
    private NoticeDao dao;

    public Notice getNoticeById(String id){
        return dao.getNoticeById(id);
    }

    @Override
    public void sendNotice(Notice notice) {
        String uuid= UUID.randomUUID().toString().replace("-","");
        notice.setId(uuid);
        dao.create(notice);
    }
}

实现controller

package top.malaoshi.notice.controllers;

import top.malaoshi.notice.entity.Notice;
import top.malaoshi.notice.service.INoticeService;
import top.malaoshi.notice.vo.CommonResult;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class NoticeCtrl {

    @Resource
    private INoticeService noticeService;
    @GetMapping(value="/getNoticeById/{id}")
    public CommonResult<Notice> getNoticeById(@PathVariable("id") String id){
        Notice notice=noticeService.getNoticeById(id);
        return new CommonResult(200,"成功!",notice);
    }
    //url后面没有/,client发请求时有没有/都可以。如果这里有/,那么client发请求时必须带上/
    @PostMapping(value="/sendNotice")
    public CommonResult sendNotice(@RequestBody Notice notice){
        noticeService.sendNotice(notice);
        System.out.println(String.format("%s 向 %s 发送通知成功!",notice.getFromUserid(),notice.getToUserid()));
        return new CommonResult(200,"成功!");
    }
}

启动notice微服务

在主启动类点右键,按下图操作:

看到下面提示表示启动成功

测试

测试sendNotice

由于必须是post请求,需要使用postman或apipost,这里使用apipost进行测试,如下图:

注意: 由于controller中@PostMapping(value="/sendNotice"),url最后没有/,所以发请求时,url后面可以有/,也可以没有/

测试getNoticeById

由于是get请求,所以通过浏览器就可以访问(用postman或apipost更好):

在浏览器输入url:http://localhost:8001/getNoticeById/306764f9a4ff4946961504f465c9498f


原文出处:/show_1EF5gWZjVPjj.html