首页 文章 精选 留言 我的

精选列表

搜索[Java表达式],共10000篇文章
优秀的个人博客,低调大师

Kafka 消息队列 Java版

消费者 apache kafka工具类,消费者Consumer类 public class Consumer { private ConsumerHandler handler; private ConsumerConfig config; private KafkaConsumer<String, String> consumer; private boolean startFlag = false; /** * 创建消费者 * * @param handler * 消费者处理类 * @param config * 消费者处理配置 */ public Consumer(ConsumerHandler handler, ConsumerConfig config) { this.handler = handler; this.config = config; init(); } /** * 初始化接收器 */ private void init() { Properties props = new Properties(); props.put("bootstrap.servers", config.getBootstrapServers());// 服务器ip:端口号,集群用逗号分隔 props.put("group.id", config.getGroupID()); /* 是否自动确认offset */ props.put("enable.auto.commit", "true"); /* 自动确认offset的时间间隔 */ props.put("auto.commit.interval.ms", config.getAutoCommitInterVal()); props.put("session.timeout.ms", config.getSessionTimeOut()); /* key的序列化类 */ props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); /* value的序列化类 */ props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); consumer = new KafkaConsumer<>(props); if (config.isProcessBeforeData()) { /* 消费者订阅的topic, 可同时订阅多个 */ consumer.subscribe(config.getTopicList(), new ConsumerRebalanceListener() { @Override public void onPartitionsRevoked(Collection<TopicPartition> partitions) { } @Override public void onPartitionsAssigned(Collection<TopicPartition> partitions) { for (TopicPartition partition : partitions) { long offset = handler.getSeek(partition.topic(), partition.partition()); if (offset >= 0) { if (consumer != null) { consumer.seek(partition, offset + 1); } } else { consumer.seekToBeginning(partitions); } } } }); start(); } else { consumer.subscribe(config.getTopicList()); } } public void start() { startFlag = true; while (startFlag) { /* 读取数据,读取超时时间为XXms */ ConsumerRecords<String, String> records = consumer.poll(config.getPollTime()); if (records.count() > 0) { long offset = 0; int partition = 0; for (ConsumerRecord<String, String> record : records) { if (record != null) { offset = record.offset(); partition = record.partition(); try { handler.processObject(record.topic(), record.partition(), record.offset(), record.value()); } catch (Exception e) { e.printStackTrace(); } } } } try { Thread.currentThread(); Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } consumer.close(); } public void stop() { startFlag = false; } } 消费者配置ConsumerConfig类 public class ConsumerConfig { private String bootstrapServers; private String groupID; private int autoCommitInterVal =1000; private int sessionTimeOut = 30000; private List<String> topicList; private boolean processBeforeData; private long pollTime = 100; public ConsumerConfig() { super(); } /** * 创建消费者配置 * @param bootstrapServers 服务器配合 格式为服务器ip:端口号,集群用逗号分隔 例如 192.168.1.1:9092,192.168.1.2:9092 * @param groupID groupID * @param autoCommitInterVal 自动提交时间单位毫秒, 默认1000 * @param sessionTimeOut 超时时间单位毫秒 , 默认30000 * @param topicList topicList列表 * @param processBeforeData 是否处理启动之前的数据,该开关需要配置consumerHandler的跨步存储使用 * @param pollTime 每次获取数据等待时间单位毫秒,默认100毫秒 */ public ConsumerConfig(String bootstrapServers, String groupID, int autoCommitInterVal, int sessionTimeOut ,List<String> topicList,boolean processBeforeData,long pollTime) { this.bootstrapServers = bootstrapServers; this.groupID = groupID; this.autoCommitInterVal = autoCommitInterVal; this.sessionTimeOut = sessionTimeOut; this.topicList = topicList; this.processBeforeData = processBeforeData; this.pollTime = pollTime; } public String getBootstrapServers() { return bootstrapServers; } public void setBootstrapServers(String bootstrapServers) { this.bootstrapServers = bootstrapServers; } public String getGroupID() { return groupID; } public void setGroupID(String groupID) { this.groupID = groupID; } public int getAutoCommitInterVal() { return autoCommitInterVal; } public void setAutoCommitInterVal(int autoCommitInterVal) { this.autoCommitInterVal = autoCommitInterVal; } public int getSessionTimeOut() { return sessionTimeOut; } public void setSessionTimeOut(int sessionTimeOut) { this.sessionTimeOut = sessionTimeOut; } public List<String> getTopicList() { return topicList; } public void setTopicList(List<String> topicList) { this.topicList = topicList; } public boolean isProcessBeforeData() { return processBeforeData; } public void setProcessBeforeData(boolean processBeforeData) { this.processBeforeData = processBeforeData; } public long getPollTime() { return pollTime; } public void setPollTime(long pollTime) { this.pollTime = pollTime; } } 消费者处理ConsumerHandler类 public interface ConsumerHandler { /** * 处理收到的消息 * @param topic 收到消息的topic名称 * @param partition 收到消息的partition内容 * @param offset 收到消息在队列中的编号 * @param value 收到的消息 */ void processObject(String topic,int partition,long offset,String value); /** * 获取跨步 * @param topic 接受消息的topic * @param partition 接受消息的partition * @return 当前topic,partition下的seek */ long getSeek(String topic , int partition); } 生产者 kafka生产者,工具Producer类 public class Producer { private ProducerConfig config ; private org.apache.kafka.clients.producer.Producer<String,String> producer; public Producer(ProducerConfig config){ this.config = config; init(); } private void init(){ Properties props = new Properties(); props.put("bootstrap.servers",config.getBootstrapServers()); props.put("acks", "all"); props.put("retries", config.getRetries()); props.put("batch.size", config.getBatchSize()); props.put("linger.ms", config.getLingerMs()); props.put("buffer.memory", config.getBufferMemory()); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); producer = new KafkaProducer<>(props); } /** * 发送消息 * @param topic 要发送的topic * @param msg */ public void sendMessage(String topic,String msg){ try { producer.send(new ProducerRecord<String, String>(config.getTopic(), String.valueOf(new Date().getTime()), msg)).get(); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (ExecutionException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } producer.flush(); } public void close(){ producer.close(); } } kafka生产者配置ProducerConfig类 public class ProducerConfig { private String bootstrapServers; private String topic; private int retries = 0; private int batchSize = 16384; private int lingerMs=1; private int bufferMemory=33554432; public ProducerConfig() { super(); } /** * 创建生产者配置文件 * @param bootstrapServers 服务器配合 格式为服务器ip:端口号,集群用逗号分隔 例如 192.168.1.1:9092,192.168.1.2:9092 * @param retries * @param batchSize * @param lingerMs * @param bufferMemory */ public ProducerConfig(String bootstrapServers,int retries, int batchSize, int lingerMs, int bufferMemory) { this.bootstrapServers = bootstrapServers; this.retries = retries; this.batchSize = batchSize; this.lingerMs = lingerMs; this.bufferMemory = bufferMemory; } public String getBootstrapServers() { return bootstrapServers; } public void setBootstrapServers(String bootstrapServers) { this.bootstrapServers = bootstrapServers; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public int getRetries() { return retries; } public void setRetries(int retries) { this.retries = retries; } public int getBatchSize() { return batchSize; } public void setBatchSize(int batchSize) { this.batchSize = batchSize; } public int getLingerMs() { return lingerMs; } public void setLingerMs(int lingerMs) { this.lingerMs = lingerMs; } public int getBufferMemory() { return bufferMemory; } public void setBufferMemory(int bufferMemory) { this.bufferMemory = bufferMemory; } } 测试 消费者处理实现ConsumerHandlerImpl类 public class ConsumerHandlerImpl implements ConsumerHandler{ /** * 处理收到的消息 * @param topic 收到消息的topic名称 * @param partition 收到消息的partition内容 * @param offset 收到消息在队列中的编号 * @param value 收到的消息 */ public void processObject(String topic,int partition,long offset,String value) { System.out.println(topic+"从kafka接收"+partition+"到"+offset+"的消息是:"+value); } /** * 获取跨步 * @param topic 接受消息的topic * @param partition 接受消息的partition * @return 当前topic,partition下的seek */ public long getSeek(String topic , int partition) { return 1; } } main方法类 public class AppResourceTest{ public static void main(String[] args){ BeanDefinitionRegistry reg=new DefaultListableBeanFactory(); PropertiesBeanDefinitionReader reader=new PropertiesBeanDefinitionReader(reg); reader.loadBeanDefinitions(new ClassPathResource("resources/kafka-consumer.properties")); reader.loadBeanDefinitions(new ClassPathResource("resources/kafka-producer.properties")); BeanFactory factory=(BeanFactory)reg; ConsumerConfig consumerConfig=(ConsumerConfig)factory.getBean("consumerConfig"); System.out.println(consumerConfig.getPollTime()); ProducerConfig producerConfig=(ProducerConfig)factory.getBean("producerConfig"); System.out.println(producerConfig.getBatchSize()); Producer producer = new Producer(producerConfig); producer.sendMessage(producerConfig.getTopic(),"s4335453453454"); producer.close(); System.out.println("consumer"); Consumer consumer = new Consumer(new ConsumerHandlerImpl(),consumerConfig); try{ Thread.currentThread(); Thread.sleep(10000); }catch(Exception e){ e.printStackTrace(); } } } 运行结果

优秀的个人博客,低调大师

JAVA学习day07

1、奇数求和练习packagecom.ghy.studyday07; /*要求:计算1-100之间的所有的奇数和1+3+5+7...+99 有1个数据,从0变到100循环int=0<=100++从0-100,范围内,找到奇数数%2==1奇数所有的奇数求和计算需要变量,保存奇数的求和 实现步骤:1.程序可以使用到的数据,预先定义好变量需要求的奇数和2.利用循环,让变量从0变化到1003.判断变量的变化情况是不是奇数4.如果是奇数,和预先定义好的变量,求和*/publicclassLoopTest{publicstaticvoidmain(String[]args){//定义变量,保存求和intsum=0;//for循环,循环中的变量,0-100for(inti=0;i<=100;i++){//对循环的变量,进行奇数的判断,%2==1if(i%2==1){//对奇数求和sum+=i;}}System.out.println(sum); //sum=0; /*for(inti=1;i<=100;i+=2){sum+=i;}System.out.println(sum);*/}} 2、计算出水仙花数即 3位数本身 = 百位数立方 + 十位数立方 + 个位数立方三位数100-999个位数的立方+十位数的立方+百位数的立方=自己本身153=111+555+333已知三位数123获取出每个数位利用除法,取模运算 实现步骤:1.定义变量才存储三个数位上的整数2.利用循环,循环中的变量,从100变化到9993.循环中得到三位数,利用算法,拆解成三个单独数位4.将三个数位立方的求和计算,计算后的求和,和他自己进行比较判断相同,就是水仙花publicclassLoopTest_1{publicstaticvoidmain(String[]args){//定义三个变量intbai=0;intshi=0;intge=0; //循环,循环变量从100-999for(inti=100;i<1000;i++){//对i,进行计算,获取出三个数位//获取百位bai=i/100;//获取十位shi=i/10%10;//获取个位ge=i%10;//对三个数位进行立方求和if(baibaibai+shishishi+gegege==i){System.out.println(i);}}}} 3、ASCII编码表数字0-9对应ASCII编码十进制为48-57, 字母a-z对应ASCII编码十进制为97-122,字母A-Z对应ASCII编码十进制为65-90 4、利用for循环打印字母表 /*利用循环,输出字母包含大写小写,52个输出A-Za-z利用编码表实现,字母和数字的对应关系A-Z65-90a-z97-122 实现步骤:1.定义变量,保存小写a,大写A2.循环26次,输出定义好的变量每次循环,变量++*/publicclassLoopTest_2{publicstaticvoidmain(String[]args){//定义变量,保存2个字母charxiaoXie='a';chardaXie='A';//定义循环,次数26次for(inti=0;i<26;i++){//输出保存字母的变量System.out.println(xiaoXie+""+daXie);daXie++;xiaoXie++;}}} 5、利用for循环打印9*9表for循环的特点: 外循环,行数 内循环,每行的个数 /*利用嵌套for循环,实现99乘法表示实现步骤:1.定义外循环控制行数2.内循环控制个数,个数,每次都在递增3.循环中输出,乘法表的格式1*3=3*/publicclassLoopTest_3{publicstaticvoidmain(String[]args){print99(9);} publicstaticvoidprint99(intn){//定义外循环,循环9次for(inti=1;i<=n;i++){//定义内循环,每次递增,循环条件,<=ifor(intj=1;j<=i;j++){//按照标准格式,输出打印System.out.print(j+""+i+"="+ij+"t");}System.out.println();}}} 6、实现数组的遍历 7、数组的逆序 不等于反向遍历 逆序的实现思想,数组最远端位置的交换 数组的指针思想: 就是数组的索引 指针是可以随时指向数组的任意一个索引的 需要两个指针 一个大指针,一个小指针 大指针=最大索引 小指针=0索引 8、选择排序原理selectSort数组中的每个元素,和其他元素进行比较换位置 元素换位需要借助第三方变量packagecom.ghy.studyday07; /*数组的排序:一般都是升序排列,元素,小到大的排列 两种排序的方式选择排序:数组的每个元素都进行比较冒泡排序:数组中相邻元素进行比较规则:比较大小,位置交换*/publicclassArrayMethodTest_2{publicstaticvoidmain(String[]args){int[]arr={3,1,4,2,56,7,0};//调用选择排序方法//selectSort(arr); //调用冒泡排序方法bubbleSort(arr);printArray(arr);}/*定义方法,实现数组的冒泡排序返回值:没有参数:数组*/publicstaticvoidbubbleSort(int[]arr){for(inti=0;i//每次内循环的比较,从0索引开始,每次都在递减for(intj=0;j//比较的索引,是j和j+1if(arr[j]>arr[j+1]){inttemp=arr[j];arr[j]=arr[j+1];arr[j+1]=temp;}}}} /*定义方法,实现数组的选择排序返回值:没有参数:数组实现步骤:1.嵌套循环实现排序外循环,控制的是一共比较了多少次内循环,控制的是每次比较了多少个元素2.判断元素的大小值小值,存储到小的索引*/publicstaticvoidselectSort(int[]arr){for(inti=0;i//内循环,是每次都在减少,修改变量的定义for(intj=i+1;j//数组的元素进行判断if(arr[i]>arr[j]){//数组的换位inttemp=arr[i];arr[i]=arr[j];arr[j]=temp;}}}} /*定义方法,实现功能返回值:void方法参数:数组*/publicstaticvoidprintArray(int[]arr){//输出一半中括号,不要换行打印System.out.print("[");//数组进行遍历for(inti=0;i//判断遍历到的元素,是不是数组的最后一个元素//如何判断循环变量到达length-1if(i==arr.length-1){//输出数组的元素和]System.out.print(arr[i]+"]");}else{//不是数组的最后一个元素,输出数组元素和逗号System.out.print(arr[i]+",");}}System.out.println();}} 9、冒泡排序功能数组的相邻元素换位置1.嵌套循环实现排序外循环,控制的是一共比较了多少次内循环,控制的是每次比较了多少个元素10、数组的折半查找前提:被查找的数组中的元素,必须有序排列

优秀的个人博客,低调大师

JAVA学习day02

1、基本数据类型四类八种 2、变量定义后,不赋值,不能使用,即必须进行赋值后才能使用; 3、自增和自减++a 和a++相等但是在计算时,有如下差别a=3b=a++b=3,a=4 若a=3c=++ac=4,a=4 4、赋值 5、打印清单实现商品库存清单案例步骤:1、实现表头,是固定数据,直接写输出语句;2、表格中间,商品数据,采用变量形式,定义变量,找对数据类型,输出所有变量3、表格尾巴,一部分数据固定另一部分:商品数据进行数学计算 */ public class Shop { public static void main(String[] args) { //输出表头固定数据 System.out.println("---------商品库存清单-----------"); System.out.println("品牌型号 尺寸 价格 库存数"); //定义表格中的数据变量 //品牌型号String 尺寸,价格double 库存int String macBrand="MacBookAir"; double macSize=13.3; double macPrice=6898.88; int macCount=5; String thinkBrand="ThinkPadT450"; double thinkSize=14; double thinkPrice=5999.88; int thinkCount=10; String asusBrand="ASUS-FL5800"; double asusSize=15.6; double asusPrice=4999.5; int asusCount=18; System.out.println(macBrand+" "+macSize+" "+macPrice+" "+macCount); System.out.println(thinkBrand+" "+thinkSize+" "+thinkPrice+" "+thinkCount); System.out.println(asusBrand+" "+asusSize+" "+asusPrice+" "+asusCount); //计算库存总数,所有商品数量库存求和 int totalCount=macCount+thinkCount+asusCount; //计算所有商品的总金额,每个商品价格*库存数 double totalMoney=macCount*macPrice+thinkCount*thinkPrice+asusCount*asusPrice; System.out.println("总库存数:"+totalCount); System.out.println("所有商品的总金额:"+totalMoney); } }

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册