百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术教程 > 正文

软件架构-Spring boot集成三方中间件Mybatis,redis,RabbitMQ

mhr18 2024-11-27 12:02 36 浏览 0 评论

继续说集成三方中间件的,主要说说统异常处理,集成Mybatis,集成redis,集成RabbitMQ。



(一)统一异常处理

创建全局异常处理类:通过使用@ControllerAdvice定义统一的异常处理类,@ExceptionHandler用来定义针对的异常类型。

1.创建统一异常Controller

@ControllerAdvice
class GlobalExceptionHandler {
 @ExceptionHandler(value = Exception.class)
 public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) 
 throws Exception {
 ModelAndView mav = new ModelAndView();
 mav.addObject("msg", "异常咯...");
 mav.setViewName("error");
 return mav;
 }
}



2.增加Controller方法,抛出异常

 @RequestMapping("/exception")
 public String hello() throws Exception {
 throw new Exception("发生错误");
 }



3.src/main/resources/templates增加error.html

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
 <meta charset="UTF-8" />
 <title>统一异常处理</title>
</head>
<body>
<h1>Error</h1>
<div th:text="${msg}"></div>
</body>
</html>



(二)集成Mybatis

1.修改pom.xml,增加依赖

<dependency>
 <groupId>org.mybatis.spring.boot</groupId>
 <artifactId>mybatis-spring-boot-starter</artifactId>
 <version>1.1.1</version><!-- 版本号必须需要 -->
 </dependency>
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 </dependency>



2.mysql的连接配置

application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/spring
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver



3.创建表t_user

CREATE TABLE `t_user` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(40) DEFAULT NULL,
 `age` int(11) DEFAULT NULL,
 `address` varchar(100) DEFAULT NULL,
 `phone` varchar(40) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;



4.创建User.java文件

包名为:com.idig8.springboot.bean

package com.idig8.springboot.bean;
/**
 * @program: springboot3d
 * @description: ${description}
 * @author: LiMing
 * @create: 2019-06-10 11:07
 **/
public class User {
 private Integer id;
 private String name;
 private Integer age;
 private String address;
 private String phone;
 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 Integer getAge() {
 return age;
 }
 public void setAge(Integer age) {
 this.age = age;
 }
 public String getAddress() {
 return address;
 }
 public void setAddress(String address) {
 this.address = address;
 }
 public String getPhone() {
 return phone;
 }
 public void setPhone(String phone) {
 this.phone = phone;
 }
}



5.创建UserMapper.java接口文件

包名为:com.idig8.springboot.mybatis

package com.idig8.springboot.mybatis;
import com.idig8.springboot.bean.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
/**
 * @program: springboot3d
 * @description: ${description}
 * @author: LiMing
 * @create: 2019-06-10 11:09
 **/
@Mapper
public interface UserMapper {
 /**根据id查询用户*/
 @Select("SELECT * FROM T_USER WHERE ID = #{id}")
 User findById(@Param("id") String id);
 /**新增用户*/
 @Insert("INSERT INTO T_USER(NAME, AGE, ADDRESS, PHONE) VALUES(#{name}, #{age}, #{address}, #{phone})")
 int insert(@Param("name") String name, @Param("age") Integer age,@Param("address") String address,@Param("phone") String phone);
}



6.测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Example.class)
public class MybatisTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testInsert() throws Exception {
 int num = userMapper.insert("zhangsan222", 20,"长沙","13100000000");
 TestCase.assertEquals(num,1);
 }
 @Test
 public void testFindById() throws Exception {
 User u = userMapper.findById("6");
 TestCase.assertNotNull(u);
 System.out.println(u.getName());
 }

(三)集成Mybatis

1.修改pom.xml,增加依赖

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

注意:旧版本spring boot中集成的redis starter为:spring-boot-starter-redis

2.redis连接配置

注意:spring.redis.database的配置通常使用0即可,Redis在配置的时候可以设置数据库数量,默认为16,可以理解为数据库的schema。

# REDIS (RedisProperties)

# Redis数据库索引(默认为0)

spring.redis.database=0

# Redis服务器地址

spring.redis.host=127.0.0.1

# Redis服务器连接端口

spring.redis.port=6379

# Redis服务器连接密码(默认为空)

spring.redis.password=

# 连接池最大连接数(使用负值表示没有限制)

spring.redis.pool.max-active=8

# 连接池最大阻塞等待时间(使用负值表示没有限制)

spring.redis.pool.max-wait=-1

# 连接池中的最大空闲连接

spring.redis.pool.max-idle=8

# 连接池中的最小空闲连接

spring.redis.pool.min-idle=0

# 连接超时时间(毫秒)

spring.redis.timeout=0

3.测试redis

注意:redis中存储对象,需要我们自己实现RedisSerializer<T>接口来对传入对象进行序列化和反序列化

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringBootMain.class)
public class SpringRedisTest {
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Test
public void testRedis() throws Exception {
ValueOperations<String, String> ops = redisTemplate.opsForValue();
ops.set("name", "zhangsan");
String value = ops.get("name");
System.out.println(value);
TestCase.assertEquals("zhangsan", value);
 }
}

(四)集成RabbitMQ

RabbitMQ是以AMQP协议实现的一种消息中间件产品,

AMQP是Advanced Message Queuing Protocol的简称,它是一个面向消息中间件的开放式标准应用层协议。

AMQP中定义了以下标准特性:

1.消息方向

2.消息队列

3.消息路由(包括:点到点模式和发布-订阅模式)

4.可靠性

5.安全性

关于AMQP 、RabbitMQ的详细内容不再这里过多介绍,本次课主要讲怎么与Spring boot集成。

  • 安装RabbitMQ

官网:https://www.rabbitmq.com/download.html

windows安装不在说了,都是傻瓜试的。linux可能比较麻烦自行百度吧。



打开浏览器并访问:http://localhost:15672/,并使用默认用户guest登录,密码也为guest,即可进入管理界面

新增管理用户并设置权限

username:springboot

password:123456



切换到springboot用户登陆,在All users中,点击Name为springboot, 进入权限设置页面



在权限设置页面,进入Permissions页面,点击“Set permission"



  • Spring Boot整合修改pom.xml,增加依赖支持
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-amqp</artifactId>
 </dependency>
  • rabbit mq连接配置
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=springboot
spring.rabbitmq.password=123456
  • 创建Rabbit配置类

配置类主要用来配置队列、交换器、路由等高级信息

import org.springframework.amqp.core.Queue;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class RabbitConfig {

@Bean

public Queue firstQueue() {

// 创建一个队列,名称为:first

return new Queue("first");

}

}

  • 创建消息产生者类

说明:通过注入AmqpTemplate接口的实例来实现消息的发送,AmqpTemplate接口定义了一套针对AMQP协议的基础操作。

@Component

public class Sender {

@Autowired

private AmqpTemplate rabbitTemplate;

public void send() {

rabbitTemplate.convertAndSend("first", "test rabbitmq message !!!");

}

}

  • 创建消息消费者

说明:

@RabbitListener注解:定义该类需要监听的队列

@RabbitHandler注解:指定对消息的处理

@Component
@RabbitListener(queues = "first")
public class Receiver {
 @RabbitHandler
 public void process(String msg) {
 System.out.println("receive msg : " + msg);
 }
}
  • 创建测试类

@RunWith(SpringJUnit4ClassRunner.class)

@SpringBootTest(classes = SpringBootMain.class)

public class RabbitmqTest {

@Autowired

private Sender sender;

@Test

public void testRabbitmq() throws Exception {

sender.send();

}

}

  • 启动主程序:SpringBootMain

控制台如果出现以下信息,则说明rabbitmq连接成功

Created new connection: rabbitConnectionFactory#29102d45:0/SimpleConnection@1dcfb5ba [delegate=amqp://springboot@127.0.0.1:5672/, localPort= 55088]

  • 运行Junit测试类
控制台输出:
receive msg : test rabbitmq message !!!
集成Rabbit MQ完毕!

PS:mq和redis之前在别的专题都说过多次了,这里就不详细的截图了。下次咱们一起说说 日志方面。

相关推荐

Spring Boot 分布式事务实现简单得超乎想象

环境:SpringBoot2.7.18+Atomikos4.x+MySQL5.71.简介关于什么是分布式事务,本文不做介绍。有需要了解的自行查找相关的资料。本篇文章将基于SpringBoot...

Qt编写可视化大屏电子看板系统15-曲线面积图

##一、前言曲线面积图其实就是在曲线图上增加了颜色填充,单纯的曲线可能就只有线条以及数据点,面积图则需要从坐标轴的左下角和右下角联合曲线形成完整的封闭区域路径,然后对这个路径进行颜色填充,为了更美观...

Doris大数据AI可视化管理工具SelectDB Studio重磅发布!

一、初识SelectDBStudioSelectDBStudio是专为ApacheDoris湖仓一体典型场景实战及其兼容数据库量身打造的GUI工具,简化数据开发与管理。二、Select...

RAD Studio 、Delphi或C++Builder设计代码编译上线缩短开发时间

#春日生活打卡季#本月,Embarcadero宣布RADStudio12.3Athens以及Delphi12.3和C++Builder12.3,提供下载。RADStudio12.3A...

Mybatis Plus框架学习指南-第三节内容

自动填充字段基本概念MyBatis-Plus提供了一个便捷的自动填充功能,用于在插入或更新数据时自动填充某些字段,如创建时间、更新时间等。原理自动填充功能通过实现com.baomidou.myba...

「数据库」Sysbench 数据库压力测试工具

sysbench是一个开源的、模块化的、跨平台的多线程性能测试工具,可以用来进行CPU、内存、磁盘I/O、线程、数据库的性能测试。目前支持的数据库有MySQL、Oracle和PostgreSQL。以...

如何选择适合公司的ERP(选erp系统的经验之谈)

很多中小公司想搞ERP,但不得要领。上ERP的目的都是歪的,如提高效率,减少人员,堵住财务漏洞等等。真正用ERP的目的是借机提升企业管理能力,找出管理上的问题并解决,使企业管理更规范以及标准化。上ER...

Manus放开注册,但Flowith才是Agent领域真正的yyds

大家好,我是运营黑客。前天,AIAgent领域的当红炸子鸡—Manus宣布全面放开注册,终于,不需要邀请码就能体验了。于是,赶紧找了个小号去确认一下。然后,额……就被墙在了外面。官方解释:中文版...

歌浓酒庄总酿酒师:我们有最好的葡萄园和最棒的酿酒师

中新网1月23日电1月18日,张裕董事长周洪江及总经理孙健一行在澳大利亚阿德莱德,完成了歌浓酒庄股权交割签约仪式,这也意味着张裕全球布局基本成型。歌浓:澳大利亚年度最佳酒庄据悉,此次张裕收购的...

软件测试进阶之自动化测试——python+appium实例

扼要:1、了解python+appium进行APP的自动化测试实例;2、能根据实例进行实训操作;本课程主要讲述用python+appium对APP进行UI自动化测试的例子。appium支持Androi...

为什么说Python是最伟大的语言?看图就知道了

来源:麦叔编程作者:麦叔测试一下你的分析能力,直接上图,自己判断一下为什么Python是最好的语言?1.有图有真相Java之父-JamesGoshlingC++之父-BjarneStrou...

如何在Eclipse中配置Python开发环境?

Eclipse是著名的跨平台集成开发环境(IDE),最初主要用来Java语言开发。但是我们通过安装不同的插件Eclipse可以支持不同的计算机语言。比如说,我们可以通过安装PyDev插件,使Eclip...

联合国岗位上新啦(联合国的岗位)

联合国人权事务高级专员办事处PostingTitleIntern-HumanRightsDutyStationBANGKOKDeadlineOct7,2025CategoryandL...

一周安全漫谈丨工信部:拟定超1亿条一般数据泄露属后果严重情节

工信部:拟定超1亿条一般数据泄露属后果严重情节11月23日,工信部官网公布《工业和信息化领域数据安全行政处罚裁量指引(试行)(征求意见稿)》。《裁量指引》征求意见稿明确了行政处罚由违法行为发生地管辖、...

oracle列转行以及C#执行语句时报错问题

oracle列转行的关键字:UNPIVOT,经常查到的怎么样转一列,多列怎么转呢,直接上代码(sshwomeyourcode):SELECTsee_no,diag_no,diag_code,...

取消回复欢迎 发表评论: