kafka搭建与使用 - SpringBoot整合kafka连接远程kafka服务 (很适合小白参考使用)

在java代码中使用kafka(springboot整合kafka) java代码maven项目实现kafka的连接及生产者、消费者的创建,以及消息的发布和订阅 阅读详情

1.官网下载zookeeper、kakfa
在这里插入图片描述
2.在linux机器上安装zookeeper、kakfa,我使用的CentOS
安装比较简单,在自己用户目录下解压:tar -zxvf 压缩文件
3.kafka自带有zookeeper,这里使用自己安装的
修改zookeeper配置
复制cp zoo_sample.cfg zoo.cfg,修改为以下点

zoo.cfg配置

# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial 
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between 
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just 
# example sakes.
dataDir=/tmp/zookeeper
# the port at which the clients will connect
clientPort=2181
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the 
# administrator guide before turning on autopurge.
#
# http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1

## Metrics Providers
#
# https://prometheus.io Metrics Exporter
#metricsProvider.className=org.apache.zookeeper.metrics.prometheus.PrometheusMetricsProvider
#metricsProvider.httpPort=7000
#metricsProvider.exportJvmInfo=true
#
#日志路径
dataLogDir=/tmp/zookeeper-log
#在阿里云的服务器上保证外网可以访问到
quorumListenOnAllIPs=true

server.properties配置

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# see kafka.server.KafkaConfig for additional details and defaults

############################# Server Basics #############################

# The id of the broker. This must be set to a unique integer for each broker.
broker.id=0

############################# Socket Server Settings #############################

# The address the socket server listens on. It will get the value returned from 
# java.net.InetAddress.getCanonicalHostName() if not configured.
#   FORMAT:
#     listeners = listener_name://host_name:port
#   EXAMPLE:
#     listeners = PLAINTEXT://your.host.name:9092
listeners=PLAINTEXT://192.168.88.200:9092

# Hostname and port the broker will advertise to producers and consumers. If not set, 
# it uses the value for "listeners" if configured.  Otherwise, it will use the value
# returned from java.net.InetAddress.getCanonicalHostName().
#advertised.listeners=PLAINTEXT://your.host.name:9092

# Maps listener names to security protocols, the default is for them to be the same. See the config documentation for more details
#listener.security.protocol.map=PLAINTEXT:PLAINTEXT,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL

# The number of threads that the server uses for receiving requests from the network and sending responses to the network
num.network.threads=3

# The number of threads that the server uses for processing requests, which may include disk I/O
num.io.threads=8

# The send buffer (SO_SNDBUF) used by the socket server
socket.send.buffer.bytes=102400

# The receive buffer (SO_RCVBUF) used by the socket server
socket.receive.buffer.bytes=102400

# The maximum size of a request that the socket server will accept (protection against OOM)
socket.request.max.bytes=104857600


############################# Log Basics #############################

# A comma separated list of directories under which to store log files
log.dirs=/tmp/kafka-logs

# The default number of log partitions per topic. More partitions allow greater
# parallelism for consumption, but this will also result in more files across
# the brokers.
num.partitions=1

# The number of threads per data directory to be used for log recovery at startup and flushing at shutdown.
# This value is recommended to be increased for installations with data dirs located in RAID array.
num.recovery.threads.per.data.dir=1

############################# Internal Topic Settings  #############################
# The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state"
# For anything other than development testing, a value greater than 1 is recommended to ensure availability such as 3.
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1

############################# Log Flush Policy #############################

# Messages are immediately written to the filesystem but by default we only fsync() to sync
# the OS cache lazily. The following configurations control the flush of data to disk.
# There are a few important trade-offs here:
#    1. Durability: Unflushed data may be lost if you are not using replication.
#    2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush.
#    3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to excessive seeks.
# The settings below allow one to configure the flush policy to flush data after a period of time or
# every N messages (or both). This can be done globally and overridden on a per-topic basis.

# The number of messages to accept before forcing a flush of data to disk
#log.flush.interval.messages=10000

# The maximum amount of time a message can sit in a log before we force a flush
#log.flush.interval.ms=1000

############################# Log Retention Policy #############################

# The following configurations control the disposal of log segments. The policy can
# be set to delete segments after a period of time, or after a given size has accumulated.
# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens
# from the end of the log.

# The minimum age of a log file to be eligible for deletion due to age
log.retention.hours=168

# A size-based retention policy for logs. Segments are pruned from the log unless the remaining
# segments drop below log.retention.bytes. Functions independently of log.retention.hours.
#log.retention.bytes=1073741824

# The maximum size of a log segment file. When this size is reached a new log segment will be created.
log.segment.bytes=1073741824

# The interval at which log segments are checked to see if they can be deleted according
# to the retention policies
log.retention.check.interval.ms=300000

############################# Zookeeper #############################

# Zookeeper connection string (see zookeeper docs for details).
# This is a comma separated host:port pairs, each corresponding to a zk
# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002".
# You can also append an optional chroot string to the urls to specify the
# root directory for all kafka znodes.
zookeeper.connect=192.168.88.200:2181

# Timeout in ms for connecting to zookeeper
zookeeper.connection.timeout.ms=18000


############################# Group Coordinator Settings #############################

# The following configuration specifies the time, in milliseconds, that the GroupCoordinator will delay the initial consumer rebalance.
# The rebalance will be further delayed by the value of group.initial.rebalance.delay.ms as new members join the group, up to a maximum of max.poll.interval.ms.
# The default value for this is 3 seconds.
# We override this to 0 here as it makes for a better out-of-the-box experience for development and testing.
# However, in production environments the default value of 3 seconds is more suitable as this will help to avoid unnecessary, and potentially expensive, rebalances during application startup.
group.initial.rebalance.delay.ms=0

producer.properties,consumer.properties配置

4.启动zookeeper、kakfa
进入zookeeper的bin目录执行启动脚本:
./zkServer.sh start
进入kakfa目录执行启动脚本已后台模式启动
bin/kafka-server-start.sh -daemon config/server.properties
5.输入jps查看是否启动正常
在这里插入图片描述
6.启动成功后,接下来可以创建2个springBoot项目,模拟生产者和消费者

为了简单可以直接选
在这里插入图片描述

生产者和消费者的配置文件信息

spring:
  kafka:
    bootstrap-servers: 192.168.88.200:9092
    producer:
      #发生错误后,消息重发的次数。
      retries: 0
      #当有多个消息需要被发送到同一个分区时,生产者会把它们放在同一个批次里。该参数指定了一个批次可以使用的内存大小,按照字节数计算。
      batch-size: 16384
      # 设置生产者内存缓冲区的大小。
      buffer-memory: 33554432
      # 键的序列化方式
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      # 值的序列化方式
      value-serializer: org.apache.kafka.common.serialization.StringSerializer
      # acks=0 : 生产者在成功写入消息之前不会等待任何来自服务器的响应。
      # acks=1 : 只要集群的首领节点收到消息,生产者就会收到一个来自服务器成功响应。
      # acks=all :只有当所有参与复制的节点全部收到消息时,生产者才会收到一个来自服务器的成功响应。
      acks: 1
    consumer:
      # 自动提交的时间间隔 在spring boot 2.X 版本中这里采用的是值的类型为Duration 需要符合特定的格式,如1S,1M,2H,5D
      auto-commit-interval: 1S
      # 该属性指定了消费者在读取一个没有偏移量的分区或者偏移量无效的情况下该作何处理:
      # latest(默认值)在偏移量无效的情况下,消费者将从最新的记录开始读取数据(在消费者启动之后生成的记录)
      # earliest :在偏移量无效的情况下,消费者将从起始位置读取分区的记录
      auto-offset-reset: earliest
      # 是否自动提交偏移量,默认值是true,为了避免出现重复数据和数据丢失,可以把它设置为false,然后手动提交偏移量
      enable-auto-commit: false
      # 键的反序列化方式
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      # 值的反序列化方式
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
    listener:
      # 在侦听器容器中运行的线程数。
      concurrency: 5
      #listner负责ack,每调用一次,就立即commit
      ack-mode: manual_immediate
      missing-topics-fatal: false

生产者客户端

package com.kafkaproducer.demo.service;


import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

@Component
public class MyKafkaProducer {
    private static final Logger log = LoggerFactory.getLogger(MyKafkaProducer.class);

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    //自定义topic
    public static final String TOPIC_TEST = "InternetJava";
    public static final String TOPIC_TEST1 = "InternetJava1";

    public void send(Object obj) {
        String obj2String = JSON.toJSONString(obj);
        log.info("准备发送消息为:{}", obj2String);
        //发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(TOPIC_TEST, obj);
        ListenableFuture<SendResult<String, Object>> future1 = kafkaTemplate.send(TOPIC_TEST1, obj);
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                //发送失败的处理
                log.error(TOPIC_TEST + " - 生产者 发送消息失败:" + throwable.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                //成功的处理
                log.info(TOPIC_TEST + " - 生产者 发送消息成功:" + stringObjectSendResult.toString());
            }
        });


    }
}

生产者前端控制器

package com.kafkaproducer.demo.controller;

import com.kafkaproducer.demo.service.MyKafkaProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/")
public class KafkaProducerController {
    @Autowired
    private MyKafkaProducer myKafkaProducer;

    @RequestMapping("message")
    public String sendMessage(String str) {
        myKafkaProducer.send(str);
        return "OK";
    }
}

消费者客户端

package com.kafkaconsumer.demo.service;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.Optional;


@Component
public class MyKafkaConsumer {
    private static final Logger log = LoggerFactory.getLogger(MyKafkaConsumer.class);

    @KafkaListener(topics = {"InternetJava"}, groupId = "test-consumer-group")
    public void topic_test(ConsumerRecord<?, ?> record, Acknowledgment ack, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {

        Optional message = Optional.ofNullable(record.value());
        if (message.isPresent()) {
            Object msg = message.get();
            log.info("topic_test 消费了: Topic:" + topic + ",Message:" + msg);
            ack.acknowledge();
        }
    }

    @KafkaListener(topics = {"InternetJava1"}, groupId = "test-consumer-group")
    public void topic_test1(ConsumerRecord<?, ?> record, Acknowledgment ack, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {

        Optional message = Optional.ofNullable(record.value());
        if (message.isPresent()) {
            Object msg = message.get();
            log.info("topic_test1 消费了: Topic:" + topic + ",Message:" + msg);
            ack.acknowledge();
        }
    }
}

启动生产者和消费者
浏览器中输入:
在这里插入图片描述
生产者打印的部分日志信息
在这里插入图片描述
消费者打印日志信息
在这里插入图片描述

7.自此项目整合结束,这里参考了网上很多资料后自行调试总结的,kafka有很多配置项(linux中安装的kafka,具体配置可以参考官网),spring整合的kafka(spring-kafka)配置可以参考spring.io官网配置,这里需要指出spring-kafka依赖的kafka需要与linux安装的kafka兼容。

附录:
直接在linux上创建topic
bin/kafka-topics.sh --create --topic InternetJava --zookeeper 192.168.88.200:2181 --partitions 1 --replication-factor 1
查询当前kafka下的所有topic
bin/kafka-topics.sh --zookeeper 192.168.88.200:2181 --list

SpringBoot整合Kafka实现生产消费 项目源码:https://gitee.com/yearns/yearns-kafka 首先我们看下项目的基本结构: KafakaConsumer.java主要为消费者,监听消息。 KafkaSender.java为生产者,发送消息。 application.properties为基本配置文件 KafaApplicationTests.java为测试生产者发送消息。 运行KafkaApplicat... 阅读详情

相关推荐

Springboot整合kafka

先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦。首先搭建两个springboot项目,一个作为生产者,一个作为消费者。页面访问,生产者发送消息。...

m0_67402235的博客 1101

远程客户端连接Kafka

一、原因描述 安装好Kafka(服务端ip为192.168.116.128(本地虚拟机)),在Linux服务器上使用kafka-console-consumer和kafka-console-producer,进行生产者和消费者测试,能进行正常的接发消息。但是通过远程客户端的作为生产者,无法与kafka服务端建立连接。 二、问题排查 1、排查是不是服务器的防火墙原因,导致服务器的9092端口不能被window连接上,在window上执行telnet 192.168.116.128 9...

yeshu2780的博客 9451

springboot整合kafka

前提:启动zookeeper、kafka,并分别创建3个主题topic1、topic2、topic3(参考:win10下操作kafka) 一、创建maven项目my-test,引入依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" ...

zsx18273117003的博客 1105

kafka配置远程连接

kafka配置远程连接

weixin_59244784的博客 2427

Kafka服务器实现远程客户端连接

Kafka是一个流行的分布式消息传递系统,它允许高吞吐量的数据流在多个应用程序或服务之间进行可靠的发布和订阅。Kafka的设计目标之一是支持远程客户端连接,这使得开发人员能够从不同的位置连接到Kafka服务器并与其进行通信。通过修改Kafka服务器的配置并使用适当的客户端代码,您可以轻松地与远程Kafka服务器进行交互。编译并运行上述Java程序,它将连接到远程Kafka服务器并发送一条消息到指定的主题。打开Kafka安装目录下的。Kafka将开始监听指定的IP地址和端口,并准备接收远程客户端的连接。

YazIdris的博客 1548

Kafka 教程:实现远程访问

本教程将介绍如何通过远程访问实现与 Kafka 的通信,并提供相应的源代码示例。通过配置 Kafka 服务器以支持远程访问,并编写相应的生产者和消费者代码,我们可以在远程环境中与 Kafka 进行通信。首先,我们需要创建一个 Kafka 生产者,用于发送消息到 Kafka 服务器。另外,我们还需创建一个 Kafka 消费者,用于从 Kafka 服务器接收消息。请注意,本示例中的代码仅用于演示目的,并没有包含完整的错误处理和异常处理逻辑。首先,我们需要在 Kafka 服务器上进行一些配置,以支持远程访问。

YazIdris的博客 2108

连接远程的kafka【linux】

连接远程的kafka【linux】

小心星的博客 2324

ADF4002分频器避坑指南:常见配置错误及解决方案

本文深入解析了ADF4002分频器在实战应用中的常见陷阱与解决方案。内容涵盖寄存器配置逻辑、硬件PCB布局要点、软件驱动时序细节及系统化调试方法,重点阐述了如何避免因配置错误导致芯片无法正常工作的问题,帮助工程师高效完成高精度频率合成系统设计。

weixin_29192141的博客 102

SpringBoot 整合 Kafka

环境 ZooKeeper、Kafka。 如果使用 docker-compose 部署 Kafka 集群,可以参考我的这篇文章 docker-compose安装Kafka集群 依赖 pom.xml 依赖文件如下:springboot 版本是 2.3.0.RELEASE 。 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <

zhangyuanshuai的博客 2万+

手把手教你用CV5200模块搭建无人机高清图传系统(含实测数据)

本文提供了一份基于CV5200模块搭建远距离无人机高清图传系统的完整实战指南。文章详细解析了系统架构、硬件连接、软件配置与优化,并分享了实地飞行测试数据。核心在于利用CV5200的LR-WiFi私有协议,在视距下实现数公里级的稳定高清视频传输,为DIY爱好者和行业应用提供了高性价比的解决方案。

day7的博客 727

知识图谱与人工智能本体论:构建机器认知的语义基石

本文探讨了知识图谱与人工智能本体论如何作为机器认知的语义基石,让AI从‘知道数据’迈向‘理解知识’。文章详细拆解了本体论的核心构件与构建方法,并阐述了从本体到知识图谱的实践路径,包括知识获取、融合、存储及推理应用,最终分析了其在智能搜索与专家系统等场景中带来的根本性重塑。

nginx7reverse的博客 915

【Java】SpringBoot快速整合Kafka

Kafka是一个开源的流式平台,用于构建实时数据流应用程序和实时数据管道。Kafka旨在处理大规模的数据流,具有高吞吐量、可扩展性、持久性和容错性的特点。

m0_64210833的博客 6571

手把手教你用Cadence Virtuoso完成LNA全套仿真:基于SpectreRF手册的实战补充

本文详细指导如何使用Cadence Virtuoso和SpectreRF完成LNA的全套仿真,涵盖噪声仿真、增益压缩、THD分析及双音IP3测量等关键步骤。针对官方手册中的常见问题,提供了12个实战解决方案,包括hbnoise函数选择、双音信号源配置等,帮助工程师高效完成射频IC设计。

weixin_29102619的博客 533

SpringBoot整合Kafka

SpringBoot整合Kafka

爱笑的boy的博客 2542

WhatsApp协议算法

我想其实有很多人还不太了WhatsApp群控,简单来说,它和我们常使用的微信聊天软件是类似的,只不过它是基于通讯录的,操作起来比较简单便捷,所以现在有很多国家都喜欢用WhatsApp。一般情况下,筛号不会造成账号被封的情况,但是呢,如果筛号的频率太快,就会被系统限制筛号能力,不再返回筛号结果,所以,筛号数量和速度一定要控制好。前天逛街突然灵光一现,为什么不试试多路访问呢,简单来说就是信道复用技术,马上跑回家,调取接口,接入通道,导入已经转换成协议的账号,成功登录!

2403_87755661的博客 1951

virtuoso如何导出def?

在DEF Out界面,填写def name,library name以及cell name ,cell view既layout,把Output "Floating Shapes" into SPECIAL NETS Section勾上,OK即可。2)在要导出的layout界面选中PAD和prBoundary(shift+左键),快捷键C copy到空cell里,这时需要调整copy过来的object坐标,让两边prBoundary的坐标相同。我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧?

m0_61544122的博客 2318

什么是kafka,如何学习kafka,整合SpringBoot

什么是kafka,如何学习kafka,整合SpringBoot

杨荧的CSDN博客 3178

【ESP32接入国产大模型之豆包】

🥳🥳🥳现在,我们在本教程中,您学习了如何使用ESP32接入语言大模型之豆包。🛹🛹🛹从而实现对外部世界进行感知,充分认识这个有机与无机的环境,后期会持续分享esp32跑freertos实用案列🥳🥳🥳科学地合理地进行创作和发挥效益,然后为人类社会发展贡献一点微薄之力。🤣🤣🤣如果你有任何问题,可以通过q group(945348278)加入鹏鹏小分队,期待与你思维的碰撞😘😘😘。

vor234的博客 1万+

SpringBoot Kafka 整合使用

前提 假设你了解过 SpringBoot 和 Kafka。 1、SpringBoot 如果对 SpringBoot 不了解的话,建议去看看DD 大佬和纯洁的微笑的系列博客。 2、Kafka Kafka 的话可以看看我前两天写的博客 :Kafka 安装及快速入门学习的话自己开台虚拟机自己手动搭建环境吧,有条件的买服务器。 注意:一定要亲自自己安装实践,接下来我们将这两个...

Fisher_yu01的博客 162

10. 重磅!Spring AI 1.0 正式发布,Java 开发者的 AI神器!

重磅!Spring AI 1.0 正式发布,Java 开发者的 AI神器! 全网最详细的Spring AI 文章,每章都会提供代码入口,让你更容易得入门和理解Spring AI 相关概念,直接节约你百分之六十的学习成本时间。

gorgor在码农 1071

深度学习工具包 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")

SpringBoot之Flume整合Kafka

目录 准备工作 Flume整合Kafka 第一步:解压kafka_2.11-2.1.0.tgz文件,将kafka-clients-2.1.0.jar包拷贝至Flume安装目录下的lib文件夹中。 第二步:在flume安装目录下的conf文件夹下创建一个jaas配置文件kafka_client_jaas.conf。 第三步:修改Flume安装...

JustryDeng 3165

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

如何从零开始优雅整合SpringBoot框架与Kafka消息中间件

由于今年的项目基本都是B/S架构的软件设计,因此被逼无奈只能开始自学JAVA WEB后端进行开发,后续会陆续总结一些技术文档,便于复现与深入学习。

进阶的乔木同学每天都在码代码 736

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

2018 Springboot整合kafka

kafka的介绍和搭建,参考: https://blog.csdn.net/qq_42606051/article/details/81407309 还有这几篇: http://kafka.apache.org/quickstart https://docs.spring.io/spring-kafka/reference/htmlsingle/#kafka http...

qq_34912478的博客 547

Spring Boot整合Kafka

Kafka作为一款分布式流处理平台,具有高吞吐量、持久性、容错性等特点,适用于构建大规模的实时数据管道。Spring Boot作为快速开发框架,提供了简化开发和部署的能力,使得与Kafka的整合变得更加容易。通过将Spring Boot与Kafka进行整合,具有以下优势异步消息处理:Kafka可以作为消息队列,实现异步消息的生产和消费,提高系统的吞吐量和响应速度。解耦和扩展性:消息队列的引入可以解耦不同系统或模块之间的依赖关系,提高系统的灵活性和可维护性。数据流处理。

q1372302825的博客 4205

搭建大型分布式服务(二十二)SpringBoot 如何优雅地整合多个kafka数据源?

系列文章目录 文章目录系列文章目录前言一、本文要点二、开发环境三、创建项目四、修改项目五、测试一下六、小结 前言 在日常开发当中,经常会遇到需要消费的topic不在同一个kafka集群内,这时候需要配置多个数据源,如何优雅地完成这个配置呢? 一、本文要点 接前文,我们已经在项目里集成了kafka。本文将介绍如何优雅地整合多个kafka数据源。系列文章完整目录 springboot 整合多个kafka数据源 springboot 整合多个消费者topic kafka listener 配置f

hanyi_的专栏 2901

kafka集群(docker环境)及springboot整合

kafka集群(docker环境)及springboot整合 一、kafka集群搭建 1、环境准备 linux环境(vm环境) docker环境 zookeeper 环境 kafka的工作依赖于zookeeper,在搭建kafka集群时,必须搭建好zookeeper集群,准备三台服务器或虚拟机比较麻烦,为了简化使用docker环境。 参考zookeeper集群(docker)搭建 如图三个zookeeper容器组成的集群 2、kafka集群搭建 1、集群规划 2、集群搭建 拉取镜像

WuHuaRou123的博客 2533
上一篇: Quartz调度 - springBoot整合quartz
下一篇: Quartz调度 - springBoot整合quartz(代码实现)
小小白兔兔
博客等级 码龄7年 47粉丝 207原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址