springboot入门案例,web开发

目录

一.SpringBoot框架入门

1.1Spring Boot 简介

1.2Spring Boot 的特性

1.3Spring Boot 四大核心

二. 入门案例

2.1 第一个 SpringBoot 项目

2.1.1 开发步骤

2.2入门案例

​​

​​

2.3 入门案例分析

2.4 Spring Boot的核心配置文件

2.4.1 核心配置格式

2.4.2 多环境配置

2.4.4 SpringBoot自定义配置

2.5 SpringBoot前端使用JSP

2.5.4 在pom.xml文件中配置以下依赖项

2.5.6 在 application.properties文件配置 SpringMVC的视图展示为jsp

 2.5.7 com.tx.springboot.controller.Indexcontroller

三 .SpringBoot框架Web开发

3.1SpringBoot集成Mybatis

3.2 SpringBoot 事务支持

3.3SpringBoot 下的Spring MVC

3.3.1 @Controller

3.3.2@RestController

3.3.3 @RequestMapping(常用)

3.3.4 @GetMapping

3.3.5 @PostMapping

3.3.6 @PutMapping

3.3.7 @DeleteMapping

3.4 Http接口请求工具Postman

3.5 SpringBoot 实现RESTful

3.5.1了解RESTful

3.5.2 SpringBoot开发RESTful

3.5.4请求冲突问题

3.5.5 RESTful原则

3.6 Spring Boot集成Redis

3.6.1 Spring Boot集成Redis

3.7 SpringBoot 集成dubbo

3.7.1 基本集成步骤

3.7.2 SpringBoot 集成SSM+Dubbo+Redis


一.SpringBoot框架入门

1.1Spring Boot 简介

        Spring Boot 是 Spring 家族中的一个全新的框架,它用来简化 Spring 应用程序的创建和
开发过程,也可以说 Spring Boot 能简化我们之前采用 SpringMVC + Spring + MyBatis 框架进行
开发的过程。
        在以往我们采用 SpringMVC + Spring + MyBatis 框架进行开发的时候,搭建和整合三大框
架,我们需要做很多工作,比如配置 web.xml ,配置 Spring ,配置 MyBatis ,并将它们整合在
一起等,而 Spring Boot 框架对此开发过程进行了革命性的颠覆,完全抛弃了繁琐的 xml
置过程,采用大量的默认配置简化我们的开发过程。
        所以采用 Spring Boot 可以非常容易和快速地创建基于 Spring 框架的应用程序,它让编
码变简单了,配置变简单了,部署变简单了,监控变简单了。正因为 Spring Boot 它化繁为
简,让开发变得极其简单和快速,所以在业界备受关注。
Spring Boot 在国内的关注趋势图: http://t.cn/ROQLquP

1.2Spring Boot 的特性

➢ 能够快速创建基于 Spring 的应用程序
➢ 能够直接使用 java main 方法启动内嵌的 Tomcat 服务器运行 Spring Boot 程序,不需
要部署 war 包文件
➢ 提供约定的 starter POM 来简化 Maven 配置,让 Maven 的配置变得简单
➢ 自动化配置,根据项目的 Maven 依赖配置, Spring boot 自动配置 Spring Spring mvc
➢ 提供了程序的健康检查等功能
➢ 基本可以完全不使用 XML 配置文件,采用注解配置

1.3Spring Boot 四大核心

  1. 自动配置
  2. 起步依赖
  3. Actuator
  4. 命令行界面

二. 入门案例

2.1 第一个 SpringBoot 项目

2.1.1 开发步骤

项目名称:001-springboot-first

1.创建一个 Module,选择类型为 Spring Initializr 快速构建

2.设置GAV坐标及pom配置信息

3.选择 Spring Boot 版本及依赖(会根据选择的依赖自动添加起步依赖并进行自动配置)

4.设置模块名称、Content Root 路径及模块文件的目录

5.项目创建完毕,如    

6.项目结构 

7.static :存放静态资源,如图片、 CSS JavaScript
templates :存放 Web 页面的模板文件
application.properties/application.yml 用于存放程序的各种依赖模块的配置信息,比如 服务
端口,数据库连接配置等

2.2入门案例

项目名称: 002-springboot-springmvc

1.创建一个新的 Module,选择类型为 Spring Initializr

2.指定GAV及pom配置信息

3.选择 Spring Boot 版本及依赖

4.修改 Content Root 路径及文件所在目录

5.对 POM.xml 文件进行解释

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--继承springboot框架的一个父项目,所有自己开发的springboot 都必须的继承-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <!--当前项目的GAV坐标-->
    <groupId>com.tx.springboot</groupId>
    <artifactId>springboot-first</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <!--maven项目名称,可以删除-->
    <name>springboot-first</name>
    <!--maven项目描述,可以删除-->
    <description>Demo project for Spring Boot</description>
    <!--maven属性配置,可以在其他地方通过${}方式引用-->
    <properties>
        <java.version>1.8</java.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

6.对SpringBoot项目结构进行说明

➢ .mvn|mvnw|mvnw.cmd:使用脚本操作执行 maven 相关命令,国内使用较少,可删
➢ .gitignore:使用版本控制工具 git 的时候,设置一些忽略提交的内容
➢ static|templates:后面模板技术中存放文件的目录
➢ application.properties: SpringBoot 的配置文件,很多集成的配置都可以在该文件中
进行配置,例如: Spring springMVC Mybatis Redis 等。目前是空的
➢ Application.java: SpringBoot 程序执行的入口,执行该程序中的 main 方法, SpringBoot
就启动了

7.创建一个springmvc的spring bootController

package com.tx.springboot.web;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SpringBootController {

    @RequestMapping("/springBoot/say")
    public @ResponseBody String say(){
        return "hello Spring boot";
    }
}
注意:新创建的类一定要位于 Application 同级目录或者下级目录,否则 SpringBoot
载不到

8.在IDEA中右键,运行Application类中的main方法

通过在控制台的输出,可以看到启动 SpringBoot 框架,会启动一个内嵌的 tomcat ,端
口号为 8080 ,上下文根为空

9.在浏览器中输入 http://localhost:8080/springBoot/say 访问

2.3 入门案例分析

➢ Spring Boot 的父级依赖 spring-boot-starter-parent 配置之后,当前的项目就是 SpringBoot 项目
➢ spring-boot-starter-parent 是一个 Springboot 的父级依赖,开发 SpringBoot 程序都需要继承该父级项目,它用来提供相关的 Maven 默认依赖,使用它之后,常用的 jar包依赖可以省去version 配置
➢ Spring Boot 提供了哪些默认 jar 包的依赖,可查看该父级依赖的 pom 文件
➢ 如果不想使用某个默认的依赖版本,可以通过 pom.xml 文件的属性配置覆盖各个依赖项,比如覆盖 Spring 版本
<properties>
        <spring-framework.version>5.0.0.RELEASE</ spring-framework.version >
</properties>
@SpringBootApplication 注解是 Spring Boot 项目的核心注解,主要作用是开启 Spring 自动配置,如果在 Application 类上去掉该注解,那么不会启动 SpringBoot 程序
➢ main 方法是一个标准的 Java 程序的 main 方法,主要作用是作为项目启动运行的入 口
➢ @Controller 及 @ResponseBody 依然是我们之前的 Spring MVC ,因为 Spring Boot 的里面依然是使用我们的 Spring MVC + Spring + MyBatis 等框架

2.4 Spring Boot的核心配置文件

        Spring boot的核心配置文件用于配置Spring Boot程序,名字必须application开始

2.4.1 核心配置格式

(1).properties文件(默认采用该文件)

项目名称: 003-springboot-port-context-path
通过修改 application.properties 配置文件,在修改默认 tomcat 端口号及项目上下文件根键值对的 properties 属性文件配置方式
#设置内嵌Tomcat端口
server.port=9090

#配置项目上下文根
server.servlet.context-path=/003-springboot-port-context-path

(2).yml文件

项目名称: 004-springboot-yml ,在 003 项目基础之上
        yml 是一种 yaml 格式的配置文件,主要采用一定的空格、换行等格式排版进行配置。
        yaml 是一种直观的能够被计算机识别的的数据序列化格式,容易被人类阅读, yaml 类似于 xml ,但是语法比 xml 简洁很多,值与前面的冒号配置项必须要有一个空格, yml 后缀也可以使用 yaml 后缀
server:
    port: 9090
    servlet:
        context-path: /004-springboot-yml
注意:当两种格式配置文件同时存在,使用的 是.properties 配置文件

2.4.2 多环境配置

        在实际开发的过程中,我们的项目会经历很多的阶段(开发-> 测试 -> 上线),每个阶段的配置也会不同,例如:端口、上下文根、数据库等,那么这个时候为了方便在不同的环境之间切换,SpringBoot 提供了多环境配置,具体步骤如下

(1) 项目名称:005-springboot-multi-environment

        为每个环境创建一个配置文件,命名必须application-环境表示.propertiest|yml

application-dev.properties

#开发环境
#设置内嵌tomcat默认端口号
server.port=8080
#设置项目的上下文根
server.servlet.context-path=/dev
#使用yml文件形式
server:
  port: 8080
  servlet:
    context-path: /dev

application-product.properties

#生产环境

#配置内嵌的tomcat默认端口号
server.port=80

#配置项目山下文根
server.servlet.context-path=/product

application-test.properties

#测试环境

#配置内嵌tomcat端口号
server.port=8081
#配置项目的上下文根
server.servlet.context-path=/test

在总配置文件application.properties进行环境的激活

#springboot主核心配置文件
#激活使用的配置文件
spring.profiles.active=product(dev,test)

yml多文档方式 — 分隔不同配置

---
server: 
  port: 8081
spring: 
  profiles: dev
---
server:
  port: 8082
spring:
  profiles: test
---
server:
  prot: 8083
spring:
  profiles: pro
---
spring:
  profiles:
      active: pro

2.4.4 SpringBoot自定义配置

案例演示:

        在 SpringBoot 的核心配置文件中,除了使用内置的配置项之外,我们还可以在自定义配置,然后采用如下注解去读取配置的属性值.

(1)@Value注解

在核心配置文件application.properties中,添加两个自定义配置项school.name 和website.

#设置内嵌tomcat端口号
server.port=8080
#设置上下文根
server.servlet.context-path=/

school.name=tx
websit=http://www.baidu.com

application.yml格式配置 

server:
    port: 9090
    servlet:
        context-path: /

school:
    name: ssm
websit: http://www.baidu.com

 在SpringbootController中的定义属性,并且使用@Value注解或者自定义配置值。

@Controller
public class IndexController {

    @Value("${school.name}")
    private String schoolName;

    @Value("${websit}")
    private String websit;

    @RequestMapping(value = "/say")
    public @ResponseBody String say() {
        return "Hello:" + schoolName + ":" + websit;
    }
}

(2)@ConfigurationProperties

案例演示:
        
        在con.tx.springboot.config包下创建ConfigInfo类,并为类加上@Componet和@ConfigurationProperties注解,加上属性prefix,作用可以区分同名配置
@Component//将此类将给spring容器进行管理
@ConfigurationProperties(prefix = "school")
public class School {

    private String name;

    private String websit;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getWebsit() {
        return websit;
    }
    public void setWebsit(String websit) {
        this.websit = websit;
    }
}

application.properties配置文件

server.port=8080
server.servlet.context-path=/

school.name=ssm
school.websit=http://www.baidu.com

application.yml配置文件

server:
    port: 9090
    servlet:
        context-path: /

school:
    name: ssm
    websit: http://www.baidu.com

在IndexController中注入School配置类 

@Controller
public class IndexController {

    @Autowired
    private School school;

    @Autowired
    private Abc abc;

    @RequestMapping(value = "/say")
    public @ResponseBody String say() {

        return "school.name="+school.getName()+"-----school.websit="+school.getWebsit() + "====abc.name"+abc.getName()+"===abc.websit="+abc.getWebsit();
    }
}

(3) 在school类中使用了ConfigurationProperties注解后,IDEA会出现一个警告不影响程序的执行

 <!--解决使用@ConfigurationProperties 注解出现警告问题-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

(4)中文乱码

如果在SpringBoot核心配置文件中有中文信息,会出现乱码

        一般在配置文件中,不建议出现中文(注释除外)
        如果有,可以先转化为 ASCII

2.5 SpringBoot前端使用JSP

2.5.4 在pom.xml文件中配置以下依赖项

  <dependencies>
        <!--SpringBoot框架web项目起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--引入SpringBoot内嵌Tomcat对jsp的解析依赖,不添加解析不了jsp-->
        <!--仅仅只是展示jsp页面,只添加以下一个依赖-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
    </dependencies>

    <build>
        <!--
            Springboot项目默认推荐使用的前端引擎是thymeleaf
            现在我们要使用springboot集成jsp,手动指定jsp最后编译的路径
            而且springboot集成jsp编译jsp的路径是springboot规定好的位置
            META-INF/resources
        -->
        <resources>
            <resource>
                <!--源文夹-->
                <directory>src/main/webapp</directory>
                <!--指定编译到META-INF/resources-->
                <targetPath>META-INF/resources</targetPath>
                <!--指定源文件夹中的哪个资源要编译进行-->
                <includes>
                    <include>*.*</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <!--SpringBoot项目编译打包的插件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

2.5.6 在 application.properties文件配置 SpringMVC的视图展示为jsp

#配置视图解析器
#其中:/ 表示目录为src/main/webapp
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

yml文件形式

#配置SpringMVC视图解析器
#其中:/ 表示目录为src/main/webapp
spring:
    mvc:
        view:
            prefix: /
            suffix: .jsp

 2.5.7 com.tx.springboot.controller.Indexcontroller

@Controller
public class IndexController {

    @RequestMapping(value = "/say")
    public ModelAndView say() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("message","Hello,SpringBoot");
        mv.setViewName("say");
        return mv;
    }
}

三 .SpringBoot框架Web开发

3.1SpringBoot集成Mybatis

实现步骤:

1.准备数据库

2.创建项目 springboot-web-mybatis

3.在pom.xml中添加相关jar依赖

4.配置application.properties数据源

5.代码实现

5.运行测试

实现:

数据库

创建项目如同前例

pom.xml中添加依赖jar

 <properties>
        <java.version>1.8</java.version>
        <!--修改父工程管理依赖的版本号-->
        <!--<mysql.version>5.1.43</mysql.version>-->
    </properties>

    <dependencies>
        <!--SpringBoot框架web项目起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--MySQL驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--<version>5.1.9</version>-->
        </dependency>

        <!--MyBatis整合SpringBoot框架的起步依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

    </dependencies>

    <build>

        <!--手动指定文件夹为resources-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

        <plugins>

            <!--mybatis 代码自动生成插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.6</version>
                <configuration>
                    <!--配置文件的位置-->
                    <configurationFile>GeneratorMapper.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>

            <!--SpringBoot项目编译打包插件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

application.properties配置数据源

#设置连接数据库的配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.154.128:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=333

代码开发

将接口和映射文件分开

 在application.properties配置文件指定映射文件的位置。

#指定MyByBatis映射文件的路径
mybatis.mapper-locations=classpath:mapper/*.xml

3.2 SpringBoot 事务支持

Spring Boot 使用事务非常简单,底层依然采用的是 Spring 本身提供的事务管理
➢ 在入口类中使用注解 @EnableTransactionManagement 开启事务支持
➢ 在访问数据库的 Service 方法上添加注解 @Transactional 即可
@SpringBootApplication
@MapperScan(basePackages = "com.abc.springboot.mapper")
@EnableTransactionManagement //开启事务支持(可选项,但@Transactional必须添加)
Public class Application{
}
@Transactional //添加此注解书名该方法添加的事务管理
public int update(Student student){
    int updateCount = studentMapper.updateByPrimaryKeySelective(student);

    System.out.println("跟新结果"+updateCount);

    //在此构造一个除数为0的异常,测试事务是否起做用
    int a = 10/0;

    return updateCount;
}

3.3SpringBoot 下的Spring MVC

        springboot下的SpringMVC和之前的SpringMVC使用是完全一样的,主要有以下注解

3.3.1 @Controller

3.3.2@RestController

Spring 4 后新增注解,是 @Controller 注解功能的增强是 @Controller @ResponseBody 的组合注解如果一个 Controller 类添加了 @RestController ,那么该 Controller 类下的所有方法都相当于添加了@ResponseBody 注解用于返回字符串或 json 数据

3.3.3 @RequestMapping(常用)

支持 Get 请求,也支持 Post 请求

3.3.4 @GetMapping

RequestMapping Get 请求方法的组合
只支持 Get 请求
Get 请求主要用于查询操作

3.3.5 @PostMapping

RequestMapping Post 请求方法的组合
只支持 Post 请求
Post 请求主要用户新增数据

3.3.6 @PutMapping

RequestMapping Put 请求方法的组合
只支持 Put 请求
Put 通常用于修改数据

3.3.7 @DeleteMapping

RequestMapping Delete 请求方法的组合
只支持 Delete 请求
通常用于删除数据

3.4 Http接口请求工具Postman

因为通过浏览器输入地址,默认发送的只能是 get 请求,通过 Postman 工具,可以模拟发送不同类型的请求,并查询结果,在安装的时候,有些机器可能会需要安装 MicroSort .NET Framework

3.5 SpringBoot 实现RESTful

3.5.1了解RESTful

REST (英文: Representational State Transfer ,简称 REST
        一种互联网软件架构设计的风格,但它并不是标准,它只是提出了一组客户端和服务器交互时的架构理念和设计原则,基于这种理念和原则设计的接口可以更简洁,更有层次,REST这个词,是 Roy Thomas Fielding 在他 2000 年的博士论文中提出的。
任何的技术都可以实现这种理念,如果一个架构符合 REST 原则,就称它为 RESTFul 架构
  • 比如我们要访问一个 http 接口:http://localhost:8080/boot/order?id=1021&status=1
  • 采用 RESTFul 风格则 http 地址为:http://localhost:8080/boot/order/1021/1

3.5.2 SpringBoot开发RESTful

        SpringBoot开发RESTful主要是几个注解实现

  1. @PathVariable (获取url中的数据,最主要的注解)
  2. @PostMapping
  3. @DeleteMapping
  4. @PutMapping
  5. @GetMapping
   @GetMapping(value = "/student/detail/{id}/{age}")
    public Object student1(@PathVariable("id") Integer id,
                           @PathVariable("age") Integer age) {
        Map<String,Object> retMap = new HashMap<>();

        retMap.put("id",id);
        retMap.put("age",age);
        return retMap;
    }
    @DeleteMapping(value = "/student/detail/{id}/{status}")
    public Object student2(@PathVariable("id") Integer id,
                           @PathVariable("status") Integer status) {
        Map<String,Object> retMap = new HashMap<>();

        retMap.put("id",id);
        retMap.put("status",status);
        return retMap;
    }

    //以上代码student1和student2会出现请求路径冲突问题
    //通常在RESTful风格中方法的请求方式会按增删改查的请求方式来区分
    //修改请求路径
    //RESUful请求风格要求路径中使用的单词都是名称,最好不要出现动词

    @DeleteMapping(value = "/student/{id}/detail/{city}")
    public Object student3(@PathVariable("id") Integer id,
                           @PathVariable("city") Integer city) {
        Map<String,Object> retMap = new HashMap<>();

        retMap.put("id",id);
        retMap.put("city",city);
        return retMap;
    }

总结:如上代码例,student1,student2形参相同,但请求方式不同来区分

        传递参数变简单了

        服务提供者对外只需要一个接口服务,而不是传统的CRUD四个接口

3.5.4请求冲突问题

改请求方式,改路径

3.5.5 RESTful原则

增post请求,删delete请求,改put请求,查get请求

请求路劲不要出现动词例如:

/boot/order/1021/1 (推荐)
/boot/queryOrder/1021/1 (不推荐)
分页,排序等操作,不需要使用斜杠传参数

3.6 Spring Boot集成Redis

3.6.1 Spring Boot集成Redis

思路梳理:完善根据学生id查询学生,先从redis缓存中查找,无法找到,在从数据库查找,然后放到redis缓存中

实现步骤

1.Mybatis逆向工程生成实体bean和数据持层

mybatis逆向工程

2.pom.xml添加redis依赖

<!--SpringBoot集成Redis的起步依赖-->
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

3.springBoot核心配置文件

#设置redis配置信息
spring.redis.host=10.0.4.10
spring.redis.port=6379
spring.redis.password=123456

-------------------------------
#使用yml文件格式
Spring:
    redis:
        host: 10.0.4.10
        password: 123456
        port: 6379

4.启动redis服务

5.编写代码

//将数据存入redis
redisTemplate.opsForValue().set(key,value);
//将数据取出
redisTemplate.opsForValue().get(key);

3.7 SpringBoot 集成dubbo

3.7.1 基本集成步骤

众所周知dubbo是一个分布式框架,我们创建一个服务接口,服务提供方,服务消费方

1.开发dubbo服务接口

(1)创建一个普通maven项目,dubbo服务接口工程

(2)创建需要的接口,例如:UserService接口

2.开发dubbo服务提供者

(1)创建SpringBoot框架的 web项目

(2)pom.xml添加依赖(Dubbo集成SpringBoot起步依赖,注册中心,接口工程)

     <!--SpringBoot框架web项目起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--Dubbo集成SpringBoot框架起步依赖-->
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!--注册中心-->
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
        </dependency>

        <!--接口工程-->
        <dependency>
            <groupId>com.tx.springboot</groupId>
            <artifactId>020-springboot-dubbo-interface</artifactId>
            <version>1.0.0</version>
        </dependency>

(3)服务提供者的核心配置

#设置内嵌Tomcat端口号
server.port=8081
#设置上下文根
server.servlet.context-path=/

#设置连接数据库的配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.154.128:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=333

#设置dubbo的配置
spring.application.name=021-springboot-dubbo-provider
#当前工程是一个服务提供者
spring.dubbo.server=true
#设置注册中心
spring.dubbo.registry=zookeeper://192.168.154.128:2181

(4)编写接口实现类

@Component
@Service(interfaceClass = StudentService.class,version = "1.0.0",timeout = 15000)
//dubbo:service interface="" version="" timeout=""
public class StudentServiceImpl implements StudentService {

    @Override
    public Integer queryAllStudentCount() {
        //调用数据持久层
        return 1250;
    }
}

(5)SpringBoot入口程序类开启dubbo配置支持注解

@SpringBootApplication      //开启spring配置
@EnableDubboConfiguration   //开启dubbo配置
public class Application {

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

(6)启动zookeeper服务

//window系统直接点击
//linux ./zkServer.sh start

3.开发dubbo服务消费者

(1)创建SpringBoot Web项目

(2)pom.xml依赖

<!--SpringBoot框架web项目起步依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!--Dubbo集成SpringBoot框架起步依赖-->
<dependency>
    <groupId>com.alibaba.spring.boot</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>

<!--注册中心-->
<dependency>
    <groupId>com.101tec</groupId>
    <artifactId>zkclient</artifactId>
    <version>0.10</version>
</dependency>

<!--接口工程-->
<dependency>
    <groupId>com.tx.springboot</groupId>
    <artifactId>020-springboot-dubbo-interface</artifactId>
    <version>1.0.0</version>
</dependency>
(3)Springboot核心配置文件
#设置内嵌Tomcat端口号
server.port=8080
server.servlet.context-path=/

#设置dubbo配置
spring.application.name=022-springboot-dubbo-consumer
#指定注册中心
spring.dubbo.registry=zookeeper://192.168.154.128:2181

(4)编写controller类,远程调用dubbo服务

@Controller
public class StudentController {
    //dubbo:reference interface="" version="" check=false
    @Reference(interfaceClass = StudentService.class,version = "1.0.0",check = false)
    private StudentService studentService;

    @RequestMapping(value = "/student/count")
    public @ResponseBody Object studentCount() {

        Integer allStudentCount = studentService.queryAllStudentCount();

        return "学生总人数为:"+allStudentCount;
    }
}

(5)在SpringBoot入口类上开启Dubbo配置

@SpringBootApplication  //开启spring注解配置
@EnableDubboConfiguration   //开启dubbo配置
public class Application {

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

(6)测试

3.7.2 SpringBoot 集成SSM+Dubbo+Redis

实现步骤:

1.创建Maven java工程,Dubbo接口

2.创建Dubbo服务提供者项目

(1)给Dubbo服务提供者添加依赖

  <!--SpringBoot框架web项目起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--Dubbo集成SpringBoot起步依赖-->
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!--注册中心-->
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
        </dependency>

        <!--MyBatis集成Springboot起步依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!--MySQL驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--SpringBoot集成Redis起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

      <!--接口工程-->
        <dependency>
            <groupId>com.bjpowernode.springboot</groupId>
            <artifactId>023-springboot-dubbo-ssm-interface</artifactId>
            <version>1.0.0</version>
        </dependency>

(2)手动指定资源配置文件路径

<!--手动指定资源配置文件路径-->
<!--目的:将数据持久层映射文件编译到classpath中-->
<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
</resources>

(3)配置Mybatis逆向工程

(4)服务提供方核心配置

#配置内嵌Tomcat端口号
server.port=8081
#设置上下文根
server.servlet.context-path=/

#设置连接数据库信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.154.128:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=333

#设置dubbo配置
spring.application.name=024-springboot-dubbo-ssm-provider
#声明当前工程为服务提供者
spring.dubbo.server=true
#设置注册中心
spring.dubbo.registry=zookeeper://192.168.154.128:2181

#设置redis配置
spring.redis.host=192.168.154.128
spring.redis.port=6379
spring.redis.password=123456

(5)配置服务提供方启动类

@SpringBootApplication
@MapperScan(basePackages = "com.tx.springboot.mapper")
@EnableDubboConfiguration   //开启dubbo配置
public class Application {

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

(6)业务接口实现类

3.创建dubbo服务消费者项目

(1)创建项目,Springboot

(2)添加依赖

  <!--SpringBoot框架web项目起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--Dubbo集成SpringBoot框架起步依赖-->
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!--zookeeper注册中心-->
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
        </dependency>

        <!--接口工程-->
        <dependency>
            <groupId>com.bjpowernode.springboot</groupId>
            <artifactId>023-springboot-dubbo-ssm-interface</artifactId>
            <version>1.0.0</version>
        </dependency>

        <!--SpringBoot集成JSP,仅仅只是展示JSP页面需要添加解析jsp页面的依赖-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

(3)核心配置

#设置内嵌Tomcat端口号
server.port=8080
server.servlet.context-path=/

#设置dubbo配置
spring.application.name=025-springboot-dubbo-ssm-consumer
spring.dubbo.registry=zookeeper://192.168.154.128:2181

#配置视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

(4)启动类配置

@SpringBootApplication
@EnableDubboConfiguration   //开启dubbo配置
public class Application {

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

(5)控制层

@Controller
public class StudentController {

    @Reference(interfaceName = "com.tx.springboot.service.StudentService",version = "1.0.0",check = false)
    private StudentService studentService;

    @RequestMapping(value = "/student/detail/{id}")
    public String studentDetail(Model model,
                                @PathVariable("id") Integer id) {

        Student student = studentService.queryStudentById(id);
        model.addAttribute("student",student);
        return "studentDetail";
    }
}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
本项目示例基于spring boot 最新版本(2.1.9)实现,Spring BootSpring Cloud 学习示例,将持续更新…… 在基于Spring BootSpring Cloud 分布微服务开发过程中,根据实际项目环境,需要选择、集成符合项目需求的各种组件和积累各种解决方案。基于这样的背景下,我开源了本示例项目,方便大家快速上手Spring BootSpring Cloud 。 每个示例都带有详细的介绍文档、作者在使用过程中踩过的坑、解决方案及参考资料,方便快速上手为你提供学习捷径,少绕弯路,提高开发效率。 有需要写关于spring bootspring cloud示例,可以给我提issue哦 ## 项目介绍 spring boot demo 是一个Spring BootSpring Cloud的项目示例,根据市场主流的后端技术,共集成了30+个demo,未来将持续更新。该项目包含helloworld(快速入门)、web(ssh项目快速搭建)、aop(切面编程)、data-redis(redis缓存)、quartz(集群任务实现)、shiro(权限管理)、oauth2(四种认证模式)、shign(接口参数防篡改重放)、encoder(用户密码设计)、actuator(服务监控)、cloud-config(配置中心)、cloud-gateway(服务网关)、email(邮件发送)、cloud-alibaba(微服务全家桶)等模块 ### 开发环境 - JDK1.8 + - Maven 3.5 + - IntelliJ IDEA ULTIMATE 2019.1 - MySql 5.7 + ### Spring Boot 模块 模块名称|主要内容 ---|--- helloworld|[spring mvc,Spring Boot项目创建,单元测试](https://github.com/smltq/spring-boot-demo/blob/master/helloworld/HELP.md) web|[ssh项目,spring mvc,过滤器,拦截器,监视器,thymeleaf,lombok,jquery,bootstrap,mysql](https://github.com/smltq/spring-boot-demo/blob/master/web/HELP.md) aop|[aop,正则,前置通知,后置通知,环绕通知](https://github.com/smltq/spring-boot-demo/blob/master/aop/HELP.md) data-redis|[lettuce,redis,session redis,YAML配置,连接池,对象存储](https://github.com/smltq/spring-boot-demo/blob/master/data-redis/HELP.md) quartz|[Spring Scheduler,Quartz,分布式调度,集群,mysql持久化等](https://github.com/smltq/spring-boot-demo/blob/master/quartz/HELP.md) shiro|[授权、认证、加解密、统一异常处理](https://github.com/smltq/spring-boot-demo/blob/master/shiro/HELP.md) sign|[防篡改、防重放、文档自动生成](https://github.com/smltq/spring-boot-demo/blob/master/sign/HELP.md) security|[授权、认证、加解密、mybatis plus使用](https://github.com/smltq/spring-boot-demo/blob/master/security/HELP.md) mybatis-plus-generator|[基于mybatisplus代码自动生成](https://github.com/smltq/spring-boot-demo/blob/master/mybatis-plus-generator) mybatis-plus-crud|[基于mybatisplus实现数据库增、册、改、查](https://github.com/smltq/spring-boot-demo/blob/master/mybatis-plus-crud) encoder|[主流加密算法介绍、用户加密算法推荐](https://github.com/smltq/spring-boot-demo/blob/master/encoder/HELP.md) actuator|[autuator介绍](https://github.com/smltq/spring-boot-demo/blob/master/actuator/README.md) admin|[可视化服务监控、使用](https://github.com/smltq/spring-boot-demo/blob/master/admin/README.md) security-oauth2-credentials|[oauth2实现密码模式、客户端模式](https://github.com/smltq/spring-boot-demo/blob/master/security-oauth2-credentials/README.md) security-oauth2-auth-code|[基于spring boot实现oauth2授权模式](https://github.com/smltq/spring-boot-demo/blob/master/security-oauth2-auth-code/README.md) mybatis-multi-datasource|[mybatis、数据库集群、读写分离、读库负载均衡](https://github.com/smltq/spring-boot-demo/blob/master/mybatis-multi-datasource) template-thymeleaf|[thymeleaf实现应用国际化示例](https://github.com/smltq/spring-boot-demo/blob/master/template-thymeleaf) mq-redis|[redis之mq实现,发布订阅模式](https://github.com/smltq/spring-boot-demo/blob/master/mq-redis) email|[email实现邮件发送](https://github.com/smltq/spring-boot-demo/blob/master/email) jGit|[java调用git命令、jgit使用等](https://github.com/smltq/spring-boot-demo/blob/master/jGit) webmagic|[webmagic实现某电影网站爬虫示例](https://github.com/smltq/spring-boot-demo/blob/master/webmagic) netty|[基于BIO、NIO等tcp服务器搭建介绍](https://github.com/smltq/spring-boot-demo/blob/master/netty) ### Spring Cloud 模块 模块名称|主要内容 ---|--- cloud-oauth2-auth-code|[基于spring cloud实现oath2授权模式](https://github.com/smltq/spring-boot-demo/blob/master/cloud-oauth2-auth-code) cloud-gateway|[API主流网关、gateway快速上手](https://github.com/smltq/spring-boot-demo/blob/master/cloud-gateway) cloud-config|[配置中心(服务端、客户端)示例](https://github.com/smltq/spring-boot-demo/blob/master/cloud-config) cloud-feign|[Eureka服务注册中心、负载均衡、声明式服务调用](https://github.com/smltq/spring-boot-demo/blob/master/cloud-feign) cloud-hystrix|[Hystrix服务容错、异常处理、注册中心示例](https://github.com/smltq/spring-boot-demo/blob/master/cloud-hystrix) cloud-zuul|[zuul服务网关、过滤器、路由转发、服务降级、负载均衡](https://github.com/smltq/spring-boot-demo/blob/master/cloud-zuul) cloud-alibaba|[nacos服务中心、配置中心、限流等使用(系列示例整理中...)](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba) #### Spring Cloud Alibaba 模块 模块名称|主要内容 ---|--- nacos|[Spring Cloud Alibaba(一)如何使用nacos服务注册和发现](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README1.md) config|[Spring Cloud Alibaba(二)配置中心多项目、多配置文件、分目录实现](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README2.md) Sentinel|[Spring Cloud Alibaba(三)Sentinel之熔断降级](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README3.md) Dubbo|[Spring Cloud Alibaba(四)Spring Cloud与Dubbo的融合](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README4.md) RocketMQ|[Spring Cloud Alibaba(五)RocketMQ 异步通信实现](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README5.md) ### 其它 模块名称|主要内容 ---|--- leetcode|[力扣题解目录](https://github.com/smltq/spring-boot-demo/blob/master/leetcode) ## Spring Boot 概述 Spring Boot简化了基于Spring的应用开发,通过少量的代码就能创建一个独立的、产品级别的Spring应用。 Spring BootSpring平台及第三方库提供开箱即用的设置,这样你就可以有条不紊地开始。多数Spring Boot应用只需要很少的Spring配置。 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Sprin
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值