6.1 Spring Boot集成mybatis

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 6.1 Spring Boot集成mybatis在SpringBoot集成MyBatis时,我们将去掉和Mybatis配置相关的xml文件配置方式,用注解和属性配置来代替这些繁杂的配置。

6.1 Spring Boot集成mybatis

在SpringBoot集成MyBatis时,我们将去掉和Mybatis配置相关的xml文件配置方式,用注解和属性配置来代替这些繁杂的配置。

本节我们使用SpringBoot集成Mybatis开发一个简易的H5性能测试的Web后台。我们采用Java,Groovy混合编程的方式。

新建gradle工程

组织工程目录结构如下

.
├── build.gradle
├── settings.gradle
└── src
    ├── main
    │   ├── groovy
    │   ├── java
    │   └── resources
    │       └── application.yml
    └── test
        ├── groovy
        ├── java
        └── resources

9 directories, 3 files

AI 代码解读

配置build.gradle

添加mybatis-spring-boot-starter依赖

compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.1.1')
AI 代码解读

该starter将会自动配置好Spring Boot集成mybatis需要的mybatis,mybatis-spring等所有依赖。这个starter的依赖树如下图所示:

其中,mybatis-spring-boot-autoconfigure会完成我们之前使用xml配置mybatis使用的sqlmap-config.xml类似如下配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="lazyLoadingEnabled" value="false"></setting>
    </settings>
</configuration>

AI 代码解读

和data-source.xml文件配置数据源dataSource和TransactionManager,

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

        <!-- 数据源定义 -->
       <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://127.0.0.1:3306/h5perf?useUnicode=true&autoReconnect=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull</value>
        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>root</value>
        </property>
    </bean>


    <!-- TransactionManager定义。 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="transactionTemplate"
          class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"/>
    </bean>


    <!-- 通过aop定义事务增强切面 -->
    <aop:config>
        <aop:pointcut id="serviceMethod" expression="execution(* com.easy.springboot.h5perf.service.*.*(..))"/>
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="false"/>
            <tx:method name="save*" rollback-for="Exception"/>
            <tx:method name="new*" rollback-for="Exception"/>
            <tx:method name="update*" rollback-for="Exception"/>
            <tx:method name="*" rollback-for="Exception"/>
        </tx:attributes>
    </tx:advice>

    <!-- MyBatis配置sqlSessionFactory, SQL Map -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 自动扫描entity目录 -->
        <property name="typeAliasesPackage" value="com.easy.springboot.h5perf.model"/>
        <!-- 显式指定Mapper文件位置 -->
        <property name="mapperLocations"
                  value="classpath:/sqlmap/*Mapper.xml"/>
        <property name="configLocation" value="classpath:sqlmap-config.xml"></property>
    </bean>
    <!-- 扫描basePackage下所有以@MyBatisRepository标识的 接口 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
          p:basePackage="com.alibaba.swork.info.common.mapper"/>

</beans>

AI 代码解读

配置application.yml

配置数据源

spring:
    datasource:
        name: h5perf
        url: jdbc:mysql://localhost:3306/h5perf?autoReconnect=true&useSSL=false
        username: root
        password: root
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
AI 代码解读

配置mybatis

mybatis:
    type-aliases-package: com.easy.springboot.h5perf.model
    configuration:
        # 开启mybatis开启数据库字段自动映射驼峰命名规则java属性
        map-underscore-to-camel-case: true
        default-fetch-size: 100
        default-statement-timeout: 30

AI 代码解读

数据库表结构

CREATE DATABASE IF NOT EXISTS `h5perf`
  DEFAULT CHARACTER SET utf8;
USE `h5perf`;

DROP TABLE IF EXISTS `test_case`;

CREATE TABLE `test_case` (
  `id`             INT(11) NOT NULL AUTO_INCREMENT,
  `container_type` VARCHAR(45)      DEFAULT NULL
  COMMENT '‘ORIGIN_WEBVIEW’,’UC_WEBVIEW’',
  `test_url`       VARCHAR(45)      DEFAULT NULL,
  `net_type`       VARCHAR(45)      DEFAULT NULL
  COMMENT '‘WIFI’,‘3G’,‘4G’',
  `gmt_created`    DATETIME         DEFAULT NULL,
  `gmt_modified`   DATETIME         DEFAULT NULL,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8;


DROP TABLE IF EXISTS `test_resource`;

CREATE TABLE `test_resource` (
  `id`            INT(11) NOT NULL AUTO_INCREMENT,
  `test_case_id`  INT(11)          DEFAULT NULL,
  `start_time`    BIGINT(11)       DEFAULT NULL,
  `resource_url`  VARCHAR(500)     DEFAULT NULL,
  `resource_type` VARCHAR(45)      DEFAULT NULL
  COMMENT 'IMG,JS,CSS,OTHER',
  `resource_time` BIGINT(11)       DEFAULT NULL
  COMMENT 'onLoadResource资源时间戳',
  `resource_size` BIGINT(11)       DEFAULT NULL
  COMMENT '资源大小',
  `gmt_created`   DATETIME         DEFAULT NULL,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8;


DROP TABLE IF EXISTS `test_time_data`;

CREATE TABLE `test_time_data` (
  `id`               INT(11) NOT NULL AUTO_INCREMENT,
  `test_case_id`     INT(11)          DEFAULT NULL,
  `on_recieve_title` VARCHAR(45)      DEFAULT NULL
  COMMENT '近似白屏时间',
  `on_page_finished` VARCHAR(45)      DEFAULT NULL
  COMMENT '页面加载完成时间',
  `dom_content_load` VARCHAR(45)      DEFAULT NULL
  COMMENT 'dom内容加载完成时间',
  `load`             VARCHAR(45)      DEFAULT NULL
  COMMENT '资源加载完成时间',
  `gmt_created`      DATETIME         DEFAULT NULL,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

AI 代码解读

Model层代码

我们在application.yml中开启了mybatis开启数据库字段自动映射驼峰命名规则java属性:

map-underscore-to-camel-case: true
AI 代码解读

所以,我们model类的属性命名规则按照驼峰命名规则。

TestCase.groovy代码:

package com.easy.springboot.h5perf.model

/**
 * Created by jack on 2017/4/22.
 */
class TestCase {
    Integer id
    String containerType
    String testUrl
    String netType
    Date gmtCreated
    Date gmtModified

    @Override
    String toString() {
        return "TestCase{" +
                "id=" + id +
                ", containerType='" + containerType + '\'' +
                ", testUrl='" + testUrl + '\'' +
                ", netType='" + netType + '\'' +
                ", gmtCreated=" + gmtCreated +
                ", gmtModified=" + gmtModified +
                '}';
    }
}


AI 代码解读

Mapper接口层代码

我们以往的通过xml配置显式指定Mapper文件位置:

<!-- 显式指定Mapper文件位置 -->
        <property name="mapperLocations"
                  value="classpath:/sqlmap/*Mapper.xml"/>
AI 代码解读

我们现在用注解方式,直接在接口上添加@Mapper注解即可。代码示例TestCaseMapper.groovy

package com.easy.springboot.h5perf.mapper

import com.easy.springboot.h5perf.model.TestCase
import org.apache.ibatis.annotations.Insert
import org.apache.ibatis.annotations.Mapper
import org.apache.ibatis.annotations.Options
import org.apache.ibatis.annotations.Param
import org.apache.ibatis.annotations.Select

@Mapper
interface TestCaseMapper {

    @Insert([
            "insert into test_case",
            "set container_type = #{t.containerType},",
            "test_url = #{t.testUrl},",
            "net_type = #{t.netType},",
            "gmt_created = #{t.gmtCreated},",
            "gmt_modified = #{t.gmtModified}"
    ])
    @Options(useGeneratedKeys = true, keyProperty = "t.id")
    int insert(@Param("t") TestCase testCase)

    @Select("select * from test_case")
    List<TestCase> findAll()

    @Select("select * from test_case where net_type=#{netType}")
    List<TestCase> findByNetType(@Param(value="netType")String netType)

    @Select("select * from test_case where id=#{id} limit 1")
    TestCase findOne(@Param(value="id")Integer id)

    int insertSelective(TestCase record)
}

AI 代码解读

Controller层代码

package com.easy.springboot.h5perf.controller

import com.easy.springboot.h5perf.model.TestCase
import com.easy.springboot.h5perf.result.Result
import com.easy.springboot.h5perf.service.TestCaseService
import com.github.pagehelper.PageInfo
import groovy.json.JsonOutput
import io.swagger.annotations.Api
import io.swagger.annotations.ApiImplicitParam
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody

/**
 * Created by jack on 2017/4/22.
 * http://springfox.github.io/springfox/docs/current/#springfox-samples
 */

//在Controller上使用@Api会生成这个Controller的整体描述
@Api(value = "测试任务管理", tags = ["测试任务管理API"], description = "描述信息")
@Controller
class TestCaseController {
    @Autowired
    TestCaseService testCaseService

    @PostMapping("/saveTestCase")
    @ResponseBody
    def saveTestCase(TestCase testCase) {
        testCase.gmtCreated = new Date()
        println("testCase===" + testCase)
        int insert = testCaseService.save(testCase)
        println("testCase===" + testCase)
        Result result = new Result()
        if (insert == 1) {
            result.success = true
            result.result = testCase
        } else {
            result.success = false
            result.result = testCase
        }
        def jsonOutput = new JsonOutput()
        println("saveTestCase result===" + jsonOutput.toJson(result))
        result
    }

    @GetMapping("/listTestCase")
    def listTestCase(Model model,
                     @RequestParam(value = "pageNo", required = false) Integer pageNo,
                     @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        def pageInfo = testCaseService.findAll(pageNo, pageSize)
        model.addAttribute("testCaseList", pageInfo.list)
        model.addAttribute("pageNo", pageInfo.pageNum)
        model.addAttribute("totalPage", pageInfo.pages)
        model.addAttribute("prePage", pageInfo.prePage)
        model.addAttribute("nextPage", pageInfo.nextPage)
        model.addAttribute("hasPreviousPage", pageInfo.hasPreviousPage)
        model.addAttribute("hasNextPage", pageInfo.hasNextPage)

        "/test_case/list"
    }

//    在具体方法上使用@ApiOperation可以生成接口的描述
    @ApiOperation(value = "list all TestCase Json", notes = "listTestCaseJson", produces = "application/json")
    @GetMapping("/listTestCaseJson")
    @ResponseBody
    def listTestCaseJson(@RequestParam(value = "pageNo", required = false) Integer pageNo,
                         @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        testCaseService.findAll(pageNo, pageSize)
    }

    @ApiOperation(value = "findOne TestCase Json", notes = "findOne TestCase", produces = "application/json")
//  在方法上使用@ApiImplicitParam可以增加对参数等的描述
    @ApiImplicitParam(name = "id",
            value = "测试任务ID",
            dataType = "Integer",//This can be the class name or a primitive
            required = true,
            paramType = "query")
//Valid values are {@code path}, {@code query}, {@code body}, {@code header} or {@code form}
    @GetMapping("/findOne")
    @ResponseBody
    def findOne(@RequestParam(value = "id", required = true) Integer id) {
        testCaseService.findOne(id)
    }

    @ApiOperation(value = "findByNetType TestCase Json", notes = "findByNetType TestCase", produces = "application/json")
//  在方法上使用@ApiImplicitParam可以增加对参数等的描述
    @ApiImplicitParam(name = "netType",
            value = "findByNetType",
            dataType = "String",//This can be the class name or a primitive
            required = true,
            paramType = "query")
    @GetMapping("/findByNetType")
    @ResponseBody
    def findByNetType(@RequestParam(value = "netType", required = false) String netType,
                      @RequestParam(value = "pageNo", required = false) Integer pageNo,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize
    ) {
        testCaseService.queryByPage(netType, pageNo, pageSize)
    }


}

AI 代码解读

使用PageHelper实现后端分页

(1)添加pagehelper-spring-boot-starter

//   pagehelper
    compile('com.github.pagehelper:pagehelper-spring-boot-starter:1.1.0')

AI 代码解读

(2)Service层代码实现

接口类 TestCaseService.groovy

package com.easy.springboot.h5perf.service

import com.easy.springboot.h5perf.model.TestCase
import com.github.pagehelper.PageInfo

/**
 * Created by jack on 2017/4/23.
 */
interface TestCaseService {
    def save(TestCase testCase)

    PageInfo<TestCase> findAll(Integer pageNo, Integer pageSize)

    TestCase findOne(Integer id)

    PageInfo<TestCase> queryByPage(String netType, Integer pageNo, Integer pageSize)

}



AI 代码解读

实现类TestCaseServiceImpl.groovy

package com.easy.springboot.h5perf.service

import com.easy.springboot.h5perf.mapper.TestCaseMapper
import com.easy.springboot.h5perf.model.TestCase
import com.github.pagehelper.PageHelper
import com.github.pagehelper.PageInfo
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * Created by jack on 2017/4/23.
 */
@Service
class TestCaseServiceImpl implements TestCaseService {
    @Autowired
    TestCaseMapper testCaseMapper;

    @Override
    def save(TestCase testCase) {
        testCaseMapper.insert(testCase)
    }

    @Override
    PageInfo<TestCase> findAll(Integer pageNo, Integer pageSize) {
        pageNo = pageNo == null ? 1 : pageNo
        pageSize = pageSize == null ? 10 : pageSize
        PageHelper.startPage(pageNo, pageSize)
        List<TestCase> testCaseList = testCaseMapper.findAll()
        //用PageInfo对结果进行包装
        PageInfo<TestCase> testCasePageInfo = new PageInfo<>(testCaseList)
        testCasePageInfo

    }

    @Override
    TestCase findOne(Integer id) {
        testCaseMapper.findOne(id)
    }

    @Override
    PageInfo<TestCase> queryByPage(String netType, Integer pageNo, Integer pageSize) {
        pageNo = pageNo == null ? 1 : pageNo
        pageSize = pageSize == null ? 10 : pageSize
        PageHelper.startPage(pageNo, pageSize)

        List<TestCase> testCaseList = testCaseMapper.findByNetType(netType)
        //用PageInfo对结果进行包装
        PageInfo<TestCase> testCasePageInfo = new PageInfo<>(testCaseList)
        testCasePageInfo
    }
}

AI 代码解读

(3)Controller层与前端代码集成

传到前端的Model层数据:

    @GetMapping("/listTestCase")
    def listTestCase(Model model,
                     @RequestParam(value = "pageNo", required = false) Integer pageNo,
                     @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        def pageInfo = testCaseService.findAll(pageNo, pageSize)
        model.addAttribute("testCaseList", pageInfo.list)
        model.addAttribute("pageNo", pageInfo.pageNum)
        model.addAttribute("totalPage", pageInfo.pages)
        model.addAttribute("prePage", pageInfo.prePage)
        model.addAttribute("nextPage", pageInfo.nextPage)
        model.addAttribute("hasPreviousPage", pageInfo.hasPreviousPage)
        model.addAttribute("hasNextPage", pageInfo.hasNextPage)

        "/test_case/list"
    }
AI 代码解读

前端使用Bootstrap pagination样式类:

    <table class="table table-hover">
        <thead>
        <th>Id</th>
        <th>testUrl</th>
        <th>containerType</th>
        <th>netType</th>
        <th>gmtCreated</th>
        </thead>
        <tbody>
        <#list testCaseList as tc >
        <tr>
            <td>${tc.id}</td>
            <td><a href="${tc.testUrl}">${tc.testUrl}</a></td>
            <td>${tc.containerType}</td>
            <td>${tc.netType}</td>
            <td>${tc.gmtCreated?string('yyyy/MM/dd HH:mm:ss')}</td>
        </tr>
        </#list>
        </tbody>
    </table>


    <div class="center">
        <ul class="pagination">
            <li><a href="/listTestCase?pageNo=${prePage}&pageSize=10">«</a></li>
        <#list 1..totalPage as index>
            <#if index=pageNo>
                <li class="active"><a href="/listTestCase?pageNo=${index}&pageSize=10">${index}</a></li>
            <#else>
                <li><a href="/listTestCase?pageNo=${index}&pageSize=10">${index}</a></li>
            </#if>
        </#list>
            <li><a href="/listTestCase?pageNo=${nextPage}&pageSize=10">»</a></li>
        </ul>
    </div>
AI 代码解读

(4)运行测试

第1页
第2页

另外,我们还可以集成Druid对数据库进行监控。相关的资料可以去网上搜索学习。本章节不再赘述。

本节完整的工程源代码:https://github.com/EasySpringBoot/h5perf

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
打赏
0
0
0
0
78
分享
相关文章
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
本文介绍在 Spring Boot 中集成 Redis 的方法。Redis 是一种支持多种数据结构的非关系型数据库(NoSQL),具备高并发、高性能和灵活扩展的特点,适用于缓存、实时数据分析等场景。其数据以键值对形式存储,支持字符串、哈希、列表、集合等类型。通过将 Redis 与 Mysql 集群结合使用,可实现数据同步,提升系统稳定性。例如,在网站架构中优先从 Redis 获取数据,故障时回退至 Mysql,确保服务不中断。
52 0
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
|
10天前
|
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
41 0
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 三大核心组件
本课程介绍如何在Spring Boot中集成Shiro框架,主要讲解Shiro的认证与授权功能。Shiro是一个简单易用的Java安全框架,用于认证、授权、加密和会话管理等。其核心组件包括Subject(认证主体)、SecurityManager(安全管理员)和Realm(域)。Subject负责身份认证,包含Principals(身份)和Credentials(凭证);SecurityManager是架构核心,协调内部组件运作;Realm则是连接Shiro与应用数据的桥梁,用于访问用户账户及权限信息。通过学习,您将掌握Shiro的基本原理及其在项目中的应用。
43 0
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
31 0
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ安装
本教程介绍ActiveMQ的安装与基本使用。首先从官网下载apache-activemq-5.15.3版本,解压后即可完成安装,非常便捷。启动时进入解压目录下的bin文件夹,根据系统选择win32或win64,运行activemq.bat启动服务。通过浏览器访问`http://127.0.0.1:8161/admin/`可进入管理界面,默认用户名密码为admin/admin。ActiveMQ支持两种消息模式:点对点(Queue)和发布/订阅(Topic)。前者确保每条消息仅被一个消费者消费,后者允许多个消费者同时接收相同消息。
38 0
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ安装
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——发布/订阅消息的生产和消费
本文详细讲解了Spring Boot中ActiveMQ的发布/订阅消息机制,包括消息生产和消费的具体实现方式。生产端通过`sendMessage`方法发送订阅消息,消费端则需配置`application.yml`或自定义工厂以支持topic消息监听。为解决点对点与发布/订阅消息兼容问题,可通过设置`containerFactory`实现两者共存。最后,文章还提供了测试方法及总结,帮助读者掌握ActiveMQ在异步消息处理中的应用。
59 0
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ集成
本文介绍了在 Spring Boot 中集成 ActiveMQ 的详细步骤。首先通过引入 `spring-boot-starter-activemq` 依赖并配置 `application.yml` 文件实现基本设置。接着,创建 Queue 和 Topic 消息类型,分别使用 `ActiveMQQueue` 和 `ActiveMQTopic` 类完成配置。随后,利用 `JmsMessagingTemplate` 实现消息发送功能,并通过 Controller 和监听器实现点对点消息的生产和消费。最后,通过浏览器访问测试接口验证消息传递的成功性。
20 0
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ—— JMS 和 ActiveMQ 介绍
本文介绍如何在Spring Boot中集成ActiveMQ,首先阐述了JMS(Java消息服务)的概念及其作为与具体平台无关的API在异步通信中的作用。接着说明了JMS的主要对象模型,如连接工厂、会话、生产者和消费者等,并指出JMS支持点对点和发布/订阅两种消息类型。随后重点讲解了ActiveMQ,作为Apache开源的消息总线,它完全支持JMS规范,适用于异步消息处理。最后,文章探讨了在Spring Boot中使用队列(Queue)和主题(Topic)这两种消息通信形式的方法。
26 0
|
10天前
|
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Spring Boot 集成 Redis
本文介绍了在Spring Boot中集成Redis的方法,包括依赖导入、Redis配置及常用API的使用。通过导入`spring-boot-starter-data-redis`依赖和配置`application.yml`文件,可轻松实现Redis集成。文中详细讲解了StringRedisTemplate的使用,适用于字符串操作,并结合FastJSON将实体类转换为JSON存储。还展示了Redis的string、hash和list类型的操作示例。最后总结了Redis在缓存和高并发场景中的应用价值,并提供课程源代码下载链接。
33 0
|
10天前
|
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 安装
本教程介绍在 VMware 虚拟机(CentOS 7)或阿里云服务器中安装 Redis 的过程,包括安装 gcc 编译环境、下载 Redis(官网或 wget)、解压安装、修改配置文件(如 bind、daemonize、requirepass 等设置)、启动 Redis 服务及测试客户端连接。通过 set 和 get 命令验证安装是否成功。适用于初学者快速上手 Redis 部署。
19 0

热门文章

最新文章