springboot2与rabbitmq整合

【RabbitMQ的监听器容器Simple和Direct】 实现和场景区别 RabbitMQ 监听器Simple、Direct并发处理方式不同,simple可能更适合动态调整消费者数量,而direct则固定每个队列的消费者数量。 阅读详情

MQ作为消息队列中间件,经常会被我们用到各种环境中,例如:异步处理、削峰、解耦等。RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件(亦称面向消息的中间件),轻量、高性能、健壮、可伸缩,是经常被使用的MQ之一。

简介

在spring中使用rabbitmq,我们可以借助Spring AMQP模块。Spring AMQP包含两部分内容:spring-amqp和spring-rabbit。spring-amqp不依赖任何特定AMQP代理实现,只为提供基于AMQP的通用抽象。目前,spring针对spring-amqp的通用抽象,只基于rabbitmq做了实现,也就是这里的spring-rabbit。在spring中使用rabbitmq是非常简单的,利用提供的AmqpTemplete或者RabbitTemplete就能够很好的完成任务,至于springboot中就更加的简单了,相关的配置已经自动完成,你可以直接使用它提供的相关的工具类完成工作。具体内容就不多说了,下面我们先来一个项目了解一下。

项目搭建

在springboot中使用rabbitmq,我们需要引入spring-boot-starter-amqp,如下:

pom.xml

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

application.properties:

#rabbitmq配置信息
spring.rabbitmq.host=localhost
spring.rabbitmq.username=php
spring.rabbitmq.password=960202

RabbitmqConfig ,@Configuration表明该文件是一个配置文件,可以被spring加载到,该文件用于配置交换机、队列、绑定等,@EnableRabbit用于开启rabbitmq。内容如下:

@Configuration
@EnableRabbit
public class RabbitmqConfig {
    @Bean("test_queue")
    public Queue queue() {
        return new Queue("test_queue");
    }
}

Producer 生产者,RabbitTemplate是spring amqp模块提供给我们用于消息的发送与接受。使用如下:

@Component
public class Producer {
    private final RabbitTemplate rabbitTemplate;
    @Autowired
    public Producer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }
    public void produce(String message) {
        this.rabbitTemplate.convertAndSend("test_queue", message);
    }
}

Consumer 消费者,@RabbitListener用作异步消息监听,是极其优雅的一种消息消费方式:

@Component
public class Consumer {
    @RabbitListener(queues = "test_queue")
    public void consume(String message) throws IOException {
        System.out.println("接受到消息:" + message);
    }
}

测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
    @Resource
    private Producer producer;
    @Test
    public void contextLoads(){
        this.producer.produce("hello world");
    }
}

大家可以发现,在springboot中使用rabbitmq是如此的简单,几个注解加上rabbitmq配置就可以解决,至于内部是如何实现的,接下来是我们需要了解的重点了。另外在这里我没有介绍rabbitmq一些常见的知识点,例如:exchange(交换机),binding(绑定),routing key(路由键)等,这些东西都是比较基础的,大家应该都比较清楚,若有需要,后续我再写一篇文章,详细介绍这些内容,本文不再描述。

源码分析

初步使用都是比较简单的,看看demo就可以写出来,但是只有了解其内部,我们才能掌握的更加熟练,遇到问题时,才能够迎刃而解,最主要的是避免项目使用过程中留坑。首先了解一下rabbitmq的属性配置内容:

RabbitProperties.java 

@ConfigurationProperties(prefix = "spring.rabbitmq")
public class RabbitProperties {
	//ip地址
	private String host = "localhost";
	//端口
	private int port = 5672;
	//用户名
	private String username = "guest";
	//密码
	private String password = "guest";
	//ssl认证信息
	private final Ssl ssl = new Ssl();
	//虚拟主机
	private String virtualHost;
	//多个rabbitmq地址,以逗号分隔
	private String addresses;
	//心跳检测 s(默认)
	@DurationUnit(ChronoUnit.SECONDS)
	private Duration requestedHeartbeat;
	//发布确认  防止消息在到达rabbitmq服务器时丢失(true,假如消息和队列是持久化的,则会在消息存入磁盘后返回确认消息)
	private boolean publisherConfirms;
	//发布返回 若消息不能正确路由到任何队列,false就会直接丢弃消息,true则会把消息返回给生产者,可以通过returnListener监听return事件
	private boolean publisherReturns;
	//连接超时时间
	private Duration connectionTimeout;
	//缓存配置 具有两种缓存方式:channel、connection 默认使用channel
	private final Cache cache = new Cache();
	//监听配置 默认两种监听容器:SIMPLE、DIRECT 默认使用SIMPLE
	private final Listener listener = new Listener();
	//templete配置 内含retry重试机制配置
	private final Template template = new Template();
}

当我们知道rabbitmq的配置属性之后,心里大致就知道了具体有哪些东西,然后我们就可以分别了解这些内容,当这些东西都了解之后,也差不多对springboot中rabbitmq的运用了解清楚了。

CachingConnectionFactory

配置信息我们已经知道了,现在我们就来看看这些配置信息是在什么时候,什么地方使用的。进入rabbitmq的自动配置类RabbitAutoConfiguration,其中存在如下片段:

/**
*仅当上下文中不存在ConnectionFactory Bean时才初始化
*该类创建CachingConnectionFactory,用于缓存connection以及channel
*默认采用channel缓存级别,缓存connection 1个,channel 25个
*/
@Configuration
@ConditionalOnMissingBean(ConnectionFactory.class)
protected static class RabbitConnectionFactoryCreator {
	@Bean
	public CachingConnectionFactory rabbitConnectionFactory(
		RabbitProperties properties,
		ObjectProvider<ConnectionNameStrategy> connectionNameStrategy)
		throws Exception {
		PropertyMapper map = PropertyMapper.get();
		//根据RabbitProperties信息封装CachingConnectionFactory对象
		CachingConnectionFactory factory = new CachingConnectionFactory(
			getRabbitConnectionFactoryBean(properties).getObject());
		map.from(properties::determineAddresses).to(factory::setAddresses);
		map.from(properties::isPublisherConfirms).to(factory::setPublisherConfirms);
		map.from(properties::isPublisherReturns).to(factory::setPublisherReturns);
		RabbitProperties.Cache.Channel channel = properties.getCache().getChannel();
		map.from(channel::getSize).whenNonNull().to(factory::setChannelCacheSize);
		map.from(channel::getCheckoutTimeout).whenNonNull().as(Duration::toMillis)
			.to(factory::setChannelCheckoutTimeout);
		//设置缓存模式(connection/channel)
		RabbitProperties.Cache.Connection connection = properties.getCache()
			.getConnection();
		map.from(connection::getMode).whenNonNull().to(factory::setCacheMode);
		//缓存大小(仅当缓存模式为connection时有效)
		map.from(connection::getSize).whenNonNull()
			.to(factory::setConnectionCacheSize);
		map.from(connectionNameStrategy::getIfUnique).whenNonNull()
			.to(factory::setConnectionNameStrategy);
		return factory;
	}
}

注意:上述我们所说的缓存,并不是channel默认只能使用25个,而是说只会缓存25个,假如使用的时候超过25个,超过的部分在使用结束后将会直接关闭。当然,若想要channel数量受到限制,可以设置channelCheckoutTimeout和channelCacheSize属性,channelCheckoutTimeout>0时,获取channel超过时间,将会抛出AmqpTimeoutException异常。

RabbitTemplete

rabbitTemplete提供多种消息发送和接受API,并且提供MessageConverter。

@Bean
@ConditionalOnSingleCandidate(ConnectionFactory.class)
@ConditionalOnMissingBean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
	PropertyMapper map = PropertyMapper.get();
	RabbitTemplate template = new RabbitTemplate(connectionFactory);
	//设置消息转换器
	MessageConverter messageConverter = this.messageConverter.getIfUnique();
	if (messageConverter != null) {
		template.setMessageConverter(messageConverter);
	}
	//开启mandatory  spring.rabbitmq.template.mandatory为null则取spring.rabbitmq.publisher-returns的值
	template.setMandatory(determineMandatoryFlag());
	RabbitProperties.Template properties = this.properties.getTemplate();
    //若开启重试机制,则将重试机制添加到RabbitTemplate
	if (properties.getRetry().isEnabled()) {
		template.setRetryTemplate(createRetryTemplate(properties.getRetry()));
	}
	//receive()操作超时时间
	map.from(properties::getReceiveTimeout).whenNonNull().as(Duration::toMillis)
		.to(template::setReceiveTimeout);
	//sendAndReceive()操作超时时间
	map.from(properties::getReplyTimeout).whenNonNull().as(Duration::toMillis)
		.to(template::setReplyTimeout);
	//设置默认交换机  缺省""
	map.from(properties::getExchange).to(template::setExchange);
	//设置默认路由键  缺省""
	map.from(properties::getRoutingKey).to(template::setRoutingKey);
	return template;
}

重试机制配置

在消费消息的时候,可能因为网络波动或其它原因导致消息手动ack,或者处理超时等,导致消息消费失败,这时我们不想直接抛出异常,而是重新获取消息进行消费,这时就可以引入重试机制(注意数据一致性),如下内容:

private RetryTemplate createRetryTemplate(RabbitProperties.Retry properties) {
        PropertyMapper map = PropertyMapper.get();
        RetryTemplate template = new RetryTemplate();
	//默认最大重试3次
	SimpleRetryPolicy policy = new SimpleRetryPolicy();
	map.from(properties::getMaxAttempts).to(policy::setMaxAttempts);
	template.setRetryPolicy(policy);
	ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
	//重试初始间隔时间 (默认0.1s)
	map.from(properties::getInitialInterval).whenNonNull().as(Duration::toMillis)
	   .to(backOffPolicy::setInitialInterval);
	//间隔时间倍数 (默认2)  下一次间隔时间=上一次间隔时间*multiplier
	map.from(properties::getMultiplier).to(backOffPolicy::setMultiplier);
	//重试最大间隔时间 (默认30s)
	map.from(properties::getMaxInterval).whenNonNull().as(Duration::toMillis)
       .to(backOffPolicy::setMaxInterval);
	template.setBackOffPolicy(backOffPolicy);
	return template;
}

RabbitAdmin

提供RabbitAdmin, 用于对交换机、队列、绑定做管理。

@Bean
@ConditionalOnSingleCandidate(ConnectionFactory.class)
@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true)
@ConditionalOnMissingBean
public AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) {
	return new RabbitAdmin(connectionFactory);
}

MessageListenerContainer

spring amqp模块中提供了两种容器供大家使用:SimpleMessageListenerContainer和DirectMessageListenerContainer,容器提供对监听的启动和停止。SimpleMessageListenerContainer中每个consumer采用专用线程,可以配置多个队列,消费者使用同一个线程处理多个队列的消息。SimpleMessageListenerContainer的并发由concurrentConsumers和maxConcurrentConsumers动态控制,concurrentConsumers代表初始固定的消费者数量,maxConcurrentConsumers代表最大的消费者数量,假设消息监听采用的是@RabbitListener,则可以通过设置concurrency=2-10达到控制消费者数量的效果。DirectMessageListenerContainer与SimpleMessageListenerContainer最大的不同,在于为每个消费者提供一个单独的channel并且消费者的逻辑不是在自己的线程池中处理的,而是在rabbit 客户端线程池处理,可以有效减少线程上下文切换所带来的资源消耗。另外DirectMessageListenerContainer在运行时添加队列或者是移除队列的性能最好,因为SimpleMessageListenerContainer会先移除所有的消费者再重新创建,而DirectMessageListenerContainer只会处理受到影响的消费者。

@RabbitListener

消息异步监听,我们可以直接在方法上通过使用该注解进行监听某个或者多个队列,例如:

    @RabbitListener(queues = "test_queue")
    public void consume(String message) throws IOException {
        System.out.println("接受到消息:" + message);
    }

@RabbitListener支持多个属性,例如:containerFactory设置容器工厂,queues设置监听队列,concurrency设置消费者并发数量等,还有一些其它的属性,大家可以自己慢慢探索。假如我们想让某个监听手动ack,可以配置此参数containerFactory,为该监听配置独立的容器工厂,虽然我们可以通过spring.rabbitmq.listener.simple.acknowledge-mode或者spring.rabbitmq.listener.direct.acknowledge-mode配置手动ack,但它是全局共享的。

总结

springboot2与rabbitmq的初步介绍,就到此为此了,目前没有给大家说有哪些具体的使用,只是简单的介绍了有哪些内容,限于篇幅,后面我们专门来描述在现实项目中,我们应该如何来使用这些内容。若上述内容有不对的地方,望大家能够指正,共同学习,共同进步。

 

springboot 整合 rabbitMQ(2) 解决重复消费问题,实现订阅者模式 阅读详情

相关推荐

springboot2.x整合rabbitmq

首先请确保你的rabbitmq服务已经打开,或者百度搜索安装 Exchange 类型 Exchange分发消息时根据类型的不同分发策略有区别,目前共四种类型:direct、fanout、topic、headers 。只说前三种模式。 1.Direct模式 消息中的路由键(routing key)如果和 Binding 中的 binding key 一致, 交换器就将消息发到对应的队列中。路由键与队列名完全匹配 2.Topic模式 topic 交换器通过模式匹配分配消息的路由键属性,将路由键.

273

RabbitMQ笔记(七)-SimpleMessageListenerContainer和DirectMessageListenerContainer

在版本2.0之前的版本中,只有一种MessageListenerContainer—SimpleMessageListenerContainer; 2.0之后有第二个容器——DirectMessageListenerContainer SimpleMessageListenerContainer 默认情况下,侦听器容器将启动单个使用者,该使用者将从队列接收消息。 在检查上一节中的表时,您将看到许多...

yingziisme的博客 2万+

LVGL按键触发回调函数的完整流程

如果是我的话我会怎么写:例如按键,我先定义一个结构体里面包含ID,事件名等和回调函数的链表节点结构体里面有具体函数的指针,也有指向下一个回调函数的链表节点的指针,初始化一个结构体变量的,通过BSP层来驱动触摸屏幕,再通过中间层与被按下时就会判断是长按还是短按还是其他,改变变量的事件例如:改成长按,生成事件包后再注册你长按的回调函数链表节点,再根据变量的事件到链表中遍历最后实现功能.父容器监听所有子列表项的点击事件,无需为每个列表项单独注册回调。的回调,打印所有事件日志,观察事件触发顺序。

solomonzw的博客 3244

rabbitMQ结合spring-boot使用三

ListenerContainer 的使用 在消费端,我们的消费监听器是运行在 监听器容器之中的( ListenerContainer ),springboot 给我们提供了两个监听器容器 SimpleMessageListenerContainer 和 DirectMessageListenerContainer 在配置文件中凡是以 spring.rabbitmq.listener.simple 开头的就是对第一个容器的配置,以 spring.rabbitmq.listener.direct 开头的是对第

qq_40506829的博客 586

UE4免费资产库新玩法:Quixel Bridge插件安装与Megascans资源导入全攻略

本文详细介绍了如何在UE4中安装Quixel Bridge插件并导入Megascans资源,帮助开发者快速获取高质量3D资产。通过分步教程和实用技巧,提升游戏或影视场景的制作效率,特别适合需要真实感环境的项目。

weixin_27729671的博客 370

Cadence 中Cutout、Design_Outline 和 Outline的区别

摘要: 在PCB设计中,Cutout、Design_Outline和Outline都与电路板外形相关但用途不同。Cutout用于定义切割区域(如孔、槽),直接影响制造;Design_Outline仅标记设计边界,作为参考不影响切割;Outline则是实际切割轮廓层,用于制造。三者区别在于:Cutout针对具体切割区域,Design_Outline是设计参考,Outline是最终切割依据。设计时需根据需求选择合适层:外形参考用Design_Outline/Outline,切割区域用Cutout。

卤煮小鱼的博客 1799

【RabbitMQ】Spring AMQP核心组件解析

Spring封装RabbitMQ的时候,它做了什么事情? 管理对象(队列,交换机,绑定) 封装方法(发送消息,接收消息) Spring AMQP 是对 Spring基于 AMQP 的消息收发解决方案,它是一个抽象层,不依赖于特定的AMQP Broker 实现和客户端的抽象,所以可以很方便地替换。比如我们可以使用spring-rabbit来实现。 <dependency> <groupId>org.springframework.amqp</groupId>

A minor 2517

BPMN2.0规范及流程引擎选型方案

本文主要简明扼要的介绍了BPMN2.0规范的内容,可让读者快速度的了解BPMN2.0所涵盖的主要内容和图形样式。也较为详细的阐述了如何绘制标准的流程图,以及在软件层面中如何实现业务流程功能,和技术选型。

比特桃 1万+

【SpringBoot】整合RabbitMQ 消费者确认模式

自动确认是指当消息一旦被消费者接收到则自动确认收到,并将消息从RabbitMQ的消息缓存中移除。如果采用了手动确认方式则需要在业务处理成功后,调用channel.basicACK(),如果出现异常则调用channel.basicNack(),让其自动重新发送消息。注意哈:上面的终端出现了死循环是因为channel.basicNack()方法的第三个参数使其消息重回队列中重新发送,但try的业务逻辑块一直有问题,所以会重复的报错,如果第三个参数是false结果如下。前者用于直接交换机,而后者用于其他交换机。

m0_65563175的博客 2398

基于机器学习和深度学习的新能源功率预测研究综述--学术论文模式--个人梳理

本文是博主根据前人的研究成果总结的机器学习和深度学习等理论方法在新能源功率预测领域的相关研究内容要点,按照学术科技论文写作的模式进行的呈现,包括文章引用等也都做了详细的批注,花了很多时间和心血,一方面是对自己学习成果的一些总结,另一方面也希望对大家有用(尽量不要直接copy哦,转载请标注,如有不当请评论或私信指出哦可再生能源的间歇性给新型电力系统的运行带来了巨大挑战,准确地预测新能源出力对于电网的安全可靠运行尤为重要。

干吧滴! 6323

形状记忆合金热机械本构模型的ABAQUS子程序实现与Fortran\_ABAQUS编程实践

本文详细介绍了如何使用ABAQUS子程序实现形状记忆合金的热机械本构模型,并通过Fortran_ABAQUS进行编程实践。我们首先介绍了问题的背景和目标,然后讲解了如何在Fortran_ABAQUS子程序中实现热变形模型、应力应变关系和相变模型,最后进行了ABAQUS模拟,并分析了模拟结果。希望通过本文的讲解,能让大家更深入理解ABAQUS子程序以及Fortran的使用,也希望能对大家在进行相关学习或研究工作时提供一些帮助。

qq_38334677的博客 1328

SpringBoot 2 快速整合 RabbitMQ

本文介绍了通过最简单方法使用 SpringBoot 2 整合 RabbitMQ,带你快速上手 RabbitMQ 的操作。

程序员小奎的博客 1111

【深度学习时间序列预测案例】零基础入门经典深度学习时间序列预测项目实战(附代码+数据集+原理介绍)

本专栏整理了《深度学习时间序列预测案例》,内包含了各种不同的基于深度学习模型的时间序列预测方法,例如LSTM、GRU、CNN(一维卷积、二维卷积)、LSTM-CNN、BiLSTM、Self-Attention、LSTM-Attention、Transformer等经典模型,包含项目原理以及源码,每一个项目实例都附带有完整的代码+数据集。

优快云 精品推荐 4万+

深入浅出 RabbitMQ - SpringBoot2.X整合RabbitMQ实战

SpringBoot整合RabbitMQ实战摘要 通过SpringBoot快速整合RabbitMQ实现消息队列功能: 环境配置:添加spring-boot-starter-amqp依赖,配置连接参数(主机/端口/虚拟主机); 核心组件:使用@Bean声明Topic交换机、持久化队列及路由绑定(支持通配符order.#); 消息生产:注入RabbitTemplate发送消息,指定交换机与路由键; 消息消费:通过@RabbitListener监听队列,自动处理消息内容; 特点:支持持久化、灵活路由、自动序列化,

chandfy的博客 1862

基于STM32L4XX、HAL库的AD7124-8BCPZ模数转换器ADC驱动程序设计

/ 公式: Voltage = (adc_value / (2^23 - 1)) * Vref。// 模式控制位[7:5]=000 (连续转换模式)// 3.2 配置通道0,使其使用AIN0(+)和AIN1(-),并关联到配置0和滤波器0。= 0x14) { // AD7124-8的ID是0x14。// 双极性操作,缓冲AINP/AINN。

zhusl6688的博客 377

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

SpringBoot2.x整合RabbitMQ

在之前的博客中https://blog.youkuaiyun.com/zhoujian_Liu/article/details/95197408,讲解了一下RabbitMQ的核心概念及如何使用web页面手动创建队列、交换器及绑定规则,在本文中将介绍SpringBoot与RabbitMQ的整合方法,使用Java代码的方式创建交换器、队列及绑定关系,并使用自定义配置替代RabbitMQ中默认JDK序列化方式,将结...

zhoujian_Liu的博客 1291

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

springboot 2.x整合rabbitmq

一、引入pom.xml &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-amqp&lt;/artifactId&gt; &lt;/dependency&gt; 二、在application.yml或a...

adminit的博客 505

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

SpringBoot2.7.4整合RabbitMq

本文介绍了Spring Boot集成RabbitMQ的三种消息模式实现方法。首先配置pom.xml添加RabbitMQ依赖,并设置application.yml连接参数。然后详细说明了直连模式(DirectExchange)、广播模式(FanoutExchange)和通配符模式(TopicExchange)的具体实现步骤,包括创建配置类定义交换机和队列、编写生产者和消费者组件、以及控制器测试接口。每种模式都提供了完整的代码示例,并说明如何通过Postman测试和查看控制台日志。

qq_35160479的博客 582

rabbitmq java集群_RabbitMQ集群整合SpringBoot2.x

RabbitMQ相信大家已经再熟悉不过了,作为业界四大主流消息中间件之一(Apache RocketMQ、Apache Kafka、Apache ActiveMQ、RabbitMQ),它具有非常好的性能和可靠性的集群模式,不仅仅在各大互联网大厂中广泛使用(比如同程艺龙、美团点评等),而且在互联网金融行业也常常被作为首选!SpringBoot作为互联网开发利器已经不需要我再过多介绍什么,接下来我们一...

weixin_28331555的博客 355

SpringBoot2x整合RabbitMQ

SpringBoot2x整合RabbitMQ

m0_65014849的博客 379

三、Springboot2.X整合RabbitMQ

文章目录Springboot2.X整合RabbitMQ Springboot2.X整合RabbitMQ 1.新建springboot工程并选择添加web组件 2.pom文件 配置 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> &lt

endless_fighting的博客 260

RabbitMQ以及整合SpringBoot2.x实战

RabbitMQ以及整合SpringBoot2.x实战 1 参考url ①https://www.bilibili.com/video/BV1dE411K7MG?from=search&seid=6293595653131678657 ②https://www.bilibili.com/video/BV1KW411F7oX?p=1 2 MQ的引言和不同MQ的特点 2.1 什么是MQ MQ(Message Quene),翻译为消息队列,别名为消息中间件,是构成生产者和消费者模型的基础。生产者不断向消息

chenweijunhy的博客 713

Springboot2整合RabbitMQ

1.RabbitMQ简介 P代表的发送的消息(Message) X代表的交换机(Exchange) 红色的代表队列(Queue) C代表着消费者(Consumer) 2.RabbitMQ发送消息的流程 Routing key:生产者在将消息发送给Exchange的时候,一般会指定一个routing key,来指定这个消息的路由规则,而这个routing key需要与Exchange Type及binding key联合使用才能最终生效。 Binding key: ...

小猪呀的博客 737

SpringBoot2整合RabbitMQ详解

开发环境: 开发工具:IntelliJ IDEA Java版本:1.8 Spring Boot版本:2.1.6.RELEASE RabbitMQ版本:3.6.9 1、开启RabbitMQ   RabbitMQ安装在本地虚拟机CentOS7上,开启RabbitMQ操作如下: #进入到系统管理目录 [root@rabbitmq ~]# cd /etc #查看当前防火墙状态 [root@rabbit...

Mr.F的博客 609

springboot2整合rabbitmq

方法得

qq_41842356的博客 511

SpringBoot2.x整合RabbitMQ(完整版)

本篇文章实现了 SpringBoot整合RabbitMQ,实现了 work模型,发布订阅模型,topic模型,confirm消息确认机制,return消息机制,TTL队列,死信队列等。整合方式有很多,比如使用 RabbitAdmin进行整合,本文介绍一个最简单的整合方式,只需要在 RabbitmqConfig.java 配置文件中进行简单配置,便可以方便的使用。相信你会喜欢这种方式的

孔明的博客 4万+
上一篇: springboot2与swagger2整合
下一篇: springboot2与定时任务的那点事
西红柿丶番茄
博客等级 码龄10年 21粉丝 41原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值