前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[基于特定逻辑的RDD键值对分区方法]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
MemCache
...例数量,或者优化业务逻辑减少不必要的请求。 --- 4. 总结 服务连接超时不可怕,可怕的是不去面对 好了,到这里,关于“服务连接超时”的问题基本就说完了。虽然MemCache确实容易让人踩坑,但只要我们用心去研究,总能找到解决方案。 最后想说的是,技术这条路没有捷径,遇到问题不要急躁,多思考、多实践才是王道。希望我的分享对你有所帮助,如果你还有什么疑问,欢迎随时来找我讨论!😄 祝大家编码愉快!
2025-04-08 15:44:16
87
雪落无痕
转载文章
...本改变文本的大小方法是把每一个text遍历。调用set_size方法设置它的属性for t in l_text:t.set_size(25)for t in p_text:t.set_size(20) 设置x,y轴刻度一致,这样饼图才能是圆的plt.axis('equal')plt.legend(loc="upper left",frameon=False,fontsize=20,borderaxespad=-5)plt.title('721法则', y=-0.1,fontsize=30,loc="center")plt.savefig("721法则.png")plt.show() 下图还是我画的,当然,没有上面那个美观。 第二个图import matplotlib.pyplot as pltplt.rcParams['font.family']='SimHei'plt.figure(figsize=(6, 9))labels = '实践与经验','交流与反馈','培训与学习'sizes = [70.0,20.0,10.0]explode = (0.1,0,0)colors = ['gray','00FFFF','FF1493']plt.pie(sizes,explode=explode,labels=labels,colors=colors,labeldistance=1.1,\autopct='%d%%',shadow=True,counterclock=False)plt.legend(loc="upper left",frameon=False,fontsize=18,borderaxespad=-5)plt.axis('equal')plt.title('721法则', y=-0.1,fontsize=18)plt.savefig("721法则.png")plt.show() 结论:我们不但要会画,还要学着画得尽可能美,实践是唯一的途径。 Python入门教程 如果你现在还是不会Python也没关系,下面我会给大家免费分享一份Python全套学习资料, 包含视频、源码、课件,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,可以和我一起来学习交 流。 ① Python所有方向的学习路线图,清楚各个方向要学什么东西 ② 600多节Python课程视频,涵盖必备基础、爬虫和数据分析 ③ 100多个Python实战案例,含50个超大型项目详解,学习不再是只会理论 ④ 20款主流手游迫解 爬虫手游逆行迫解教程包 ⑤ 爬虫与反爬虫攻防教程包,含15个大型网站迫解 ⑥ 爬虫APP逆向实战教程包,含45项绝密技术详解 ⑦ 超300本Python电子好书,从入门到高阶应有尽有 ⑧ 华为出品独家Python漫画教程,手机也能学习 ⑨ 历年互联网企业Python面试真题,复习时非常方便 👉Python学习视频600合集👈 观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。 👉实战案例👈 光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。 👉100道Python练习题👈 检查学习结果。 👉面试刷题👈 资料领取 上述这份完整版的Python全套学习资料已经上传CSDN官方,朋友们如果需要可以微信扫描下方CSDN官方认证二维码输入“领取资料” 即可领取 好文推荐 了解python的前景:https://blog.csdn.net/weixin_49891576/article/details/127187029 了解python的兼职:https://blog.csdn.net/weixin_49891576/article/details/127125308 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_49891576/article/details/130861900。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-06-04 23:38:21
105
转载
Kafka
...。 2.2 分区与副本机制 Kafka通过分区(Partition)来分摊负载,同时通过副本(Replica)机制来提高可用性和容错性。每个分区可以有多个副本,其中一个为主副本,其余为从副本。 java AdminClient adminClient = AdminClient.create(props); ListTopicsOptions options = new ListTopicsOptions(); options.listInternal(true); Set topics = adminClient.listTopics(options).names().get(); System.out.println("Topics: " + topics); 这段代码用于列出Kafka集群中的所有主题及其副本信息。通过这种方式,你可以检查每个主题的副本分布情况。 3. 生产者端的可靠性保障 作为生产者,我们需要确保发送出去的消息能够安全到达Kafka集群。这涉及到一些关键配置: - acks:控制生产者的确认级别。设置为"all"时,意味着必须等待所有副本确认。 - retries:指定重试次数。如果网络抖动导致消息未送达,Kafka会自动重试。 - linger.ms:控制批量发送的时间间隔。默认值为0毫秒,即立即发送。 java Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("acks", "all"); props.put("retries", 3); props.put("linger.ms", 5); props.put("batch.size", 16384); Producer producer = new KafkaProducer<>(props); for (int i = 0; i < 100; i++) { producer.send(new ProducerRecord<>("my-topic", Integer.toString(i), Integer.toString(i))); } producer.close(); 在这个例子中,我们设置了retries=3和linger.ms=5,这意味着即使遇到短暂的网络问题,Kafka也会尝试最多三次重试,并且会在5毫秒内累积多条消息一起发送。 4. 消费者端的可靠性保障 消费者端同样需要关注可靠性问题。Kafka 有两种消费模式,一个叫 earliest,一个叫 latest。简单来说,earliest 就是从头开始补作业,把之前没看过的消息全都读一遍;而 latest 则是直接从最新的消息开始看,相当于跳过之前的存档,直接进入直播频道。 java Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "test-group"); props.put("enable.auto.commit", "true"); props.put("auto.commit.interval.ms", "1000"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer consumer = new KafkaConsumer<>(props); consumer.subscribe(Arrays.asList("my-topic")); while (true) { ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord record : records) { System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value()); } } 这段代码展示了如何订阅一个主题并持续拉取消息。注意这里启用了自动提交功能,这样就不需要手动管理偏移量了。 5. 总结与反思 通过今天的讨论,我相信大家对Kafka的消息可靠性有了更深的理解。Kafka能从一堆消息队列系统里脱颖而出,靠的就是它在设计的时候就脑补了各种“灾难片”场景,比如数据爆炸、服务器宕机啥的,然后还给配齐了神器,专门对付这些麻烦事儿。 然而,正如任何技术一样,Kafka也不是万能的。在实际应用中,我们还需要结合具体的业务需求来调整配置参数。比如说啊,在那种超级忙、好多请求同时涌过来的场景下,就得调整一下每次处理的任务量,别一下子搞太多,慢慢来可能更稳。但要是你干的事特别讲究速度,晚一秒钟都不行的那种,那就得想办法把发东西的时间间隔调短点,越快越好! 总之,Kafka的强大之处在于它允许我们灵活地调整策略以适应不同的工作负载。希望这篇文章能帮助你在实践中更好地利用Kafka的优势!如果你有任何疑问或想法,欢迎随时交流哦~
2025-04-11 16:10:34
95
幽谷听泉
转载文章
... (4)选择类型为“基于对话框”,下一步或者完成。 (5)找到厂家提供的光盘资料,路径如下(64位库为例)。 A.进入厂商提供的光盘资料找到“8.PC函数”文件夹,并点击进入。 B.选择“函数库2.1”文件夹。 C.选择“Windows平台”文件夹。 D.根据需要选择对应的函数库这里选择64位库。 E.解压C++的压缩包,里面有C++对应的函数库。 F.函数库具体路径如下。 (6)将厂商提供的C++的库文件和相关头文件复制到新建的项目里面。 (7)在项目中添加静态库和相关头文件。 A.先右击项目文件,接着依次选择:“添加”→“现有项”。 B.在弹出的窗口中依次添加静态库和相关头文件。 (8)声明用到的头文件和定义控制器连接句柄。 至此项目新建完成,可进行MFC项目开发。 2.查看PC函数手册,熟悉相关函数接口 (1)PC函数手册也在光盘资料里面,具体路径如下:“光盘资料\8.PC函数\函数库2.1\ZMotion函数库编程手册 V2.1.pdf” (2)链接控制器,获取链接句柄。 ZAux_OpenEth()接口说明: (3)振镜运动接口。 为振镜运动单独封装了一个运动接口,使用movescanabs指令进行运动,采用FORCE_SPEED参数设置运动过程中的速度,运动过程中基本不存在加减速过程,支持us级别的时间控制。 3. MFC开发控制器双振镜运动例程 (1)例程界面如下。 (2) 链接按钮的事件处理函数中调用链接控制器的接口函数ZAux_OpenEth(),与控制器进行链接,链接成功后启动定时器1监控控制器状态。 //网口链接控制器void CSingle_move_Dlg::OnOpen(){char buffer[256]; int32 iresult;//如果已经链接,则先断开链接if(NULL != g_handle){ZAux_Close(g_handle);g_handle = NULL;}//从IP下拉框中选择获取IP地址GetDlgItemText(IDC_IPLIST,buffer,255);buffer[255] = '\0';//开始链接控制器iresult = ZAux_OpenEth(buffer, &g_handle);if(ERR_SUCCESS != iresult){g_handle = NULL;MessageBox(_T("链接失败"));SetWindowText("未链接");return;}//链接成功开启定时器1SetWindowText("已链接");SetTimer( 1, 100, NULL ); } (3)通过定时器监控控制器状态 。 void CSingle_move_Dlg::OnTimer(UINT_PTR nIDEvent) {// TODO: Add your message handler code here and/or call defaultif(NULL == g_handle){MessageBox(_T("链接断开"));return ;}if(1 == nIDEvent){CString string;float position = 0;ZAux_Direct_GetDpos( g_handle,m_nAxis,&position); //获取当前轴位置string.Format("振镜X1轴位置:%.2f", position );GetDlgItem( IDC_CURPOS )->SetWindowText( string );float NowSp = 0;ZAux_Direct_GetVpSpeed( g_handle,m_nAxis,&NowSp); //获取当前轴速度string.Format("振镜X1轴速度:%.2f", NowSp );GetDlgItem( IDC_CURSPEED)->SetWindowText( string );ZAux_Direct_GetDpos(g_handle, m_nAxis+1, &position); //获取当前轴位置string.Format("振镜Y1轴位置:%.2f", position);GetDlgItem(IDC_CURPOS2)->SetWindowText(string);ZAux_Direct_GetVpSpeed(g_handle, m_nAxis+1, &NowSp); //获取当前轴速度string.Format("振镜Y1轴速度:%.2f", NowSp);GetDlgItem(IDC_CURSPEED2)->SetWindowText(string);ZAux_Direct_GetDpos(g_handle, m_nAxis + 2, &position); //获取当前轴位置string.Format("振镜X2轴位置:%.2f", position);GetDlgItem(IDC_CURPOS3)->SetWindowText(string);NowSp = 0;ZAux_Direct_GetVpSpeed(g_handle, m_nAxis + 2, &NowSp); //获取当前轴速度string.Format("振镜X2轴速度:%.2f", NowSp);GetDlgItem(IDC_CURSPEED3)->SetWindowText(string);ZAux_Direct_GetDpos(g_handle, m_nAxis + 3, &position); //获取当前轴位置string.Format("振镜Y2轴位置:%.2f", position);GetDlgItem(IDC_CURPOS4)->SetWindowText(string);ZAux_Direct_GetVpSpeed(g_handle, m_nAxis + 3, &NowSp); //获取当前轴速度string.Format("振镜Y2轴速度:%.2f", NowSp);GetDlgItem(IDC_CURSPEED4)->SetWindowText(string);int status = 0; ZAux_Direct_GetIfIdle(g_handle, m_nAxis,&status); //判断当前轴状态if (status == -1){GetDlgItem( IDC_CURSTATE )->SetWindowText( "当前状态:停 止" );}else{GetDlgItem( IDC_CURSTATE )->SetWindowText( "当前状态:运动中" );} }CDialog::OnTimer(nIDEvent);} (4)通过启动按钮的事件处理函数获取编辑框的移动轨迹,并设置振镜轴参数操作振镜轴运动。 void CSingle_move_Dlg::OnStart() //启动运动{if(NULL == g_handle){MessageBox(_T("链接断开状态"));return ;}UpdateData(true);//刷新参数int status = 0; ZAux_Direct_GetIfIdle(g_handle, m_nAxis,&status); //判断当前轴状态 if (status == 0) //已经在运动中{ return;} //设定轴类型 1-脉冲轴类型 for (int i = 4; i < 8; i++){ZAux_Direct_SetAtype(g_handle, i, m_Atype);ZAux_Direct_SetMerge(g_handle,i,1);//设置脉冲当量ZAux_Direct_SetUnits(g_handle, i, m_units);//设定速度,加减速ZAux_Direct_SetLspeed(g_handle, i, m_lspeed);ZAux_Direct_SetSpeed(g_handle, i, m_speed);ZAux_Direct_SetForceSpeed(g_handle, i, m_speed);ZAux_Direct_SetAccel(g_handle, i, m_acc);ZAux_Direct_SetDecel(g_handle, i, m_dec);//设定S曲线时间 设置为0表示梯形加减速 ZAux_Direct_SetSramp(g_handle, i, m_sramp);}//使用MOVESCANABS运动int axislist[2] = { 4,5 };float dposlist[2] = { 0,0 };ZAux_MoveScanAbs(2, axislist, dposlist);CString str;GetDlgItem(IDC_EDIT_POSX1)->GetWindowText(str);float dbx = atof(str);GetDlgItem(IDC_EDIT_POSY1)->GetWindowText(str);float dby = atof(str);dposlist[0] = dbx;dposlist[1] = dby;ZAux_MoveScanAbs(2, axislist, dposlist);GetDlgItem(IDC_EDIT_POSX2)->GetWindowText(str);dbx = atof(str);GetDlgItem(IDC_EDIT_POSY2)->GetWindowText(str);dby = atof(str);dposlist[0] = dbx;dposlist[1] = dby;ZAux_MoveScanAbs(2, axislist, dposlist);GetDlgItem(IDC_EDIT_POSX3)->GetWindowText(str);dbx = atof(str);GetDlgItem(IDC_EDIT_POSY3)->GetWindowText(str);dby = atof(str);dposlist[0] = dbx;dposlist[1] = dby;ZAux_MoveScanAbs(2, axislist, dposlist);GetDlgItem(IDC_EDIT_POSX4)->GetWindowText(str);dbx = atof(str);GetDlgItem(IDC_EDIT_POSY4)->GetWindowText(str);dby = atof(str);dposlist[0] = dbx;dposlist[1] = dby;ZAux_MoveScanAbs(2, axislist, dposlist);//第二个振镜运动//使用MOVESCANABS运动axislist[0] = 6;axislist[1] = 7;dposlist[0] = 0;dposlist[1] = 0;ZAux_MoveScanAbs(2, axislist, dposlist);GetDlgItem(IDC_EDIT_POSX5)->GetWindowText(str);dbx = atof(str);GetDlgItem(IDC_EDIT_POSY5)->GetWindowText(str);dby = atof(str);dposlist[0] = dbx;dposlist[1] = dby;ZAux_MoveScanAbs(2, axislist, dposlist);GetDlgItem(IDC_EDIT_POSX6)->GetWindowText(str);dbx = atof(str);GetDlgItem(IDC_EDIT_POSY6)->GetWindowText(str);dby = atof(str);dposlist[0] = dbx;dposlist[1] = dby;ZAux_MoveScanAbs(2, axislist, dposlist);GetDlgItem(IDC_EDIT_POSX7)->GetWindowText(str);dbx = atof(str);GetDlgItem(IDC_EDIT_POSY7)->GetWindowText(str);dby = atof(str);dposlist[0] = dbx;dposlist[1] = dby;ZAux_MoveScanAbs(2, axislist, dposlist);GetDlgItem(IDC_EDIT_POSX8)->GetWindowText(str);dbx = atof(str);GetDlgItem(IDC_EDIT_POSY8)->GetWindowText(str);dby = atof(str);dposlist[0] = dbx;dposlist[1] = dby;ZAux_MoveScanAbs(2, axislist, dposlist);UpdateData(false); } (5) 通过断开按钮的事件处理函数来断开与控制卡的连接。 void CSingle_move_Dlg::OnClose() //断开链接{// TODO: Add your control notification handler code hereif(NULL != g_handle){KillTimer(1); //关定时器KillTimer(2);ZAux_Close(g_handle);g_handle = NULL;SetWindowText("未链接");} } (6)通过坐标清零按钮的事件处理函数移动振镜轴回零到中心零点位置,不直接使用dpos=0,修改振镜轴坐标。 void CSingle_move_Dlg::OnZero() //清零坐标{if(NULL == g_handle){MessageBox(_T("链接断开状态"));return ;}// TODO: Add your control notification handler code hereint axislist[2] = { 4,5 };float dposlist[2] = { 0 };ZAux_Direct_MoveAbs(g_handle,2,axislist,dposlist); //设置运动回零点} 三调试与监控 编译运行例程,同时通过ZDevelop软件连接控制器对控制器状态进行监控 。 ZDevelop软件连接控制器监控控制器的状态,查看振镜轴对应参数,并可搭配示波器检测双振镜轨迹。 设置振镜轴运动,首先需要将轴类型配置成21振镜轴类型,并对应配置振镜轴的速度加减速等参数才可操作振镜进行运动。 通过ZDevelop软件的示波器监控双振镜运动运行轨迹。 视频演示。 开放式激光振镜+运动控制器(六)-双振镜运动 本次,正运动技术开放式激光振镜+运动控制器(六):双振镜运动,就分享到这里。 更多精彩内容请关注“正运动小助手”公众号,需要相关开发环境与例程代码,请咨询正运动技术销售工程师:400-089-8936。 本文由正运动技术原创,欢迎大家转载,共同学习,一起提高中国智能制造水平。文章版权归正运动技术所有,如有转载请注明文章来源。 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_57350300/article/details/123402200。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-04 17:33:09
338
转载
转载文章
...机制,允许员工在未来特定时间内以预先约定的价格购买公司股票的权利。在本文所述的互联网公司中,很多公司向员工提供股票期权作为福利之一,旨在让员工分享公司的成长收益,增强归属感,并鼓励员工与公司共同长期发展。
2023-01-11 22:59:19
529
转载
转载文章
...f 华为的数字化转型方法论 华为如何实施数字化转型(附PPT) 超详细280页Docker实战文档!开放下载 华为大数据解决方案(PPT) 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_45727359/article/details/119745674。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-06-28 17:16:54
62
转载
转载文章
...记录。在创建容器时,基于镜像最上面加上一层可读写层,从而保证了容器具有独立的存储空间,可以在不改变镜像本身的情况下进行持久化存储或者动态调整。
2023-11-26 15:47:20
538
转载
转载文章
...简介 特征工程 计算方法Gauss-Jordan消去法求线性方程组的解 使用(VAE)生成建模,理解可变自动编码器背后的数学原理 视觉SLAM入门 -- 学习笔记 - Part2 带你入门nodejs第一天——node基础语法及使用 python3数据结构_Python3-数据结构 debezium-connect-oracle使用 相关数值分析多种算法代码 android iphone treeview,Android之IphoneTreeView带组指示器的ExpandableListView效果 nginx rewrite功能使用 3-3 OneHot编码 JavaWeb:shiro入门小案例 MySQL的定义、操作、控制、查询语言的用法 MongoDB入门学习(三):MongoDB的增删查改 赋值、浅复制和深复制解析 以及get/set应用 他是吴恩达导师,被马云聘为「达摩院」首座 Jordan 标准型定理 列主元的Gauss-Jordan消元法-python实现 Jordan 块的几何 若尔当型(The Jordan form) 第七章 其他神经网络类型 解决迁移系统后无法配置启用WindowsRE环境的问题 宝塔面板迁移系统盘/www到数据盘/home 使用vmware vconverter从物理机迁移系统到虚拟机P2V 本篇文章为转载内容。原文链接:https://blog.csdn.net/m0_62695120/article/details/124510157。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-08 20:01:49
68
转载
转载文章
...并恢复必要信息的项目特定分析器来解决这个问题,FFI Navigator就这样诞生了,作者仍然是陈天奇博士。 安装方式如下: 建议使用源码安装git clone https://github.com/tqchen/ffi-navigator.git 安装python依赖cd ffi-navigator/pythonpython setyp.py install vscode需要安装FFI Navigator插件,直接搜索安装即可(安装到服务器端)。 最后需要在.vscode/setting.json进行配置,内容如下: {"python.analysis.extraPaths": ["${workspaceFolder}/python"], // 添加额外导入路径, 告诉pylance自定义的python库在哪里"ffi_navigator.pythonpath": "/home/liyanpeng/anaconda3/envs/tvmenv/bin/python", // 配置FFI Navigator"python.defaultInterpreterPath": "/home/liyanpeng/anaconda3/envs/tvmenv/bin/python","files.associations": {"type_traits": "cpp","fstream": "cpp","thread": "cpp",".tcc": "cpp"} } 更详细内容可以参考项目链接。 结束语 对于vscode的使用技巧及C/C++相关的配置,这里不再详细的介绍了,感兴趣的小伙伴们可以了解下。 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_42730750/article/details/126723224。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-12 20:04:26
87
转载
转载文章
...辑API,开发者可以基于此构建更为丰富的个性化设置功能。此举不仅简化了开发流程,也为用户提供更多样化的头像定制选项。 此外,从安全性和隐私保护角度出发,欧盟GDPR等相关法规对用户数据处理提出了严格要求,这也促使各平台在设计头像上传功能时,必须兼顾到用户信息的安全存储与传输。众多企业开始采用加密上传、权限控制等手段,确保用户头像数据的安全性。 综上所述,在当前互联网环境下,用户头像处理技术正不断迭代创新,以满足日益增长的个性化需求和严格的隐私保护规范。无论是大型社交平台的技术突破,还是各类开发框架对头像上传功能的优化改进,都为我们提供了丰富的实践案例与参考思路,值得广大开发者持续关注并深入研究。
2023-07-18 10:58:17
268
转载
转载文章
...码的语法元数据。类、方法、变量、参数、包都可以被注解,可用来将信息元数据与程序元素进行关联。目前很多开源库都使用到了注解,最熟悉的ButtonKnife中的@ViewInject(R.id.x)就可以替代findViewId,不懂这一块技术的同学第一眼看上去肯定会一脸懵逼,下面会手把手带大家写出ButtonKnife的注解使用。使用注解可以简化代码,提高开发效率。本文简单介绍下注解的使用,并对几个 Android 开源库的注解使用原理进行简析。 1、作用 标记,用于告诉编译器一些信息 ; 编译时动态处理,如动态生成代码 ; 运行时动态处理,如得到注解信息。 2、分类 标准 Annotation, 包括 Override, Deprecated, SuppressWarnings。也都是Java自带的几个 Annotation,上面三个分别表示重写函数,不鼓励使用(有更好方式、使用有风险或已不在维护),忽略某项 Warning; 元 Annotation ,@Retention, @Target, @Inherited, @Documented。元 Annotation 是指用来定义 Annotation 的 Annotation,在后面 Annotation 自定义部分会详细介绍含义; 自定义 Annotation , 表示自己根据需要定义的 Annotation,定义时需要用到上面的元 Annotation 这里只是一种分类而已,也可以根据作用域分为源码时、编译时、运行时 Annotation。通过 @interface 定义,注解名即为自定义注解名。 一、自定义注解 例如,注解@MethodInfo: @Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@Inheritedpublic @interface MethodInfo {String author() default "annotation@gmail.com";String date();int version() default 1;} 使用到了元Annotation: @Documented 是否会保存到 Javadoc 文档中 ; @Retention 保留时间,可选值 SOURCE(源码时),CLASS(编译时),RUNTIME(运行时),默认为 CLASS,值为 SOURCE 大都为 Mark Annotation,这类 Annotation 大都用来校验,比如 Override, Deprecated, SuppressWarnings ; @Target 用来指定修饰的元素,如 CONSTRUCTOR:用于描述构造器、FIELD:用于描述域、LOCAL_VARIABLE:用于描述局部变量、METHOD:用于描述方法、PACKAGE:用于描述包、PARAMETER:用于描述参数、TYPE:用于描述类、接口(包括注解类型) 或enum声明。 @Inherited 是否可以被继承,默认为 false。 注解的参数名为注解类的方法名,且: 所有方法没有方法体,没有参数没有修饰符,实际只允许 public & abstract 修饰符,默认为 public ,不允许抛异常; 方法返回值只能是基本类型,String, Class, annotation, enumeration 或者是他们的一维数组; 若只有一个默认属性,可直接用 value() 函数。一个属性都没有表示该 Annotation 为 Mark Annotation。 public class App {@MethodInfo(author = “annotation.cn+android@gmail.com”,date = "2011/01/11",version = 2)public String getAppName() {return "appname";} } 调用自定义MethodInfo 的示例,这里注解的作用实际是给方法添加相关信息: author、date、version 。 二、实战注解Butter Knife 首先,先定义一个ViewInject注解。 public @interface ViewInject { int value() default -1;} 紧接着,为刚自定义注解添加元注解。 @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface ViewInject {int value() default -1;} 再定义一个注解LayoutInject @Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface LayoutInject {int value() default -1;} 定义一个基础的Activity。 package cn.wsy.myretrofit.annotation;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import java.lang.reflect.Field;public class InjectActivity extends AppCompatActivity {private int mLayoutId = -1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);displayInjectLayout();displayInjectView();}/ 解析注解view id/private void displayInjectView() {if (mLayoutId <=0){return ;}Class<?> clazz = this.getClass();Field[] fields = clazz.getDeclaredFields();//获得声明的成员变量for (Field field : fields) {//判断是否有注解try {if (field.getAnnotations() != null) {if (field.isAnnotationPresent(ViewInject.class)) {//如果属于这个注解//为这个控件设置属性field.setAccessible(true);//允许修改反射属性ViewInject inject = field.getAnnotation(ViewInject.class);field.set(this, this.findViewById(inject.value()));} }} catch (Exception e) {Log.e("wusy", "not found view id!");} }}/ 注解布局Layout id/private void displayInjectLayout() {Class<?> clazz = this.getClass();if (clazz.getAnnotations() != null){if (clazz.isAnnotationPresent(LayouyInject.class)){LayouyInject inject = clazz.getAnnotation(LayouyInject.class);mLayoutId = inject.value();setContentView(mLayoutId);} }} } 首先,这里是根据映射实现设置控件的注解,java中使用反射的机制效率性能并不高。这里只是举例子实现注解。ButterKnife官方申明不是通过反射机制,因此效率会高点。 package cn.wsy.myretrofit;import android.os.Bundle;import android.widget.TextView;import cn.wsy.myretrofit.annotation.InjectActivity;import cn.wsy.myretrofit.annotation.LayouyInject;import cn.wsy.myretrofit.annotation.ViewInject;@LayoutInject(R.layout.activity_main)public class MainActivity extends InjectActivity {@ViewInject(R.id.textview)private TextView textView;@ViewInject(R.id.textview1)private TextView textview1;@ViewInject(R.id.textview2)private TextView textview2;@ViewInject(R.id.textview3)private TextView textview3;@ViewInject(R.id.textview4)private TextView textview4;@ViewInject(R.id.textview5)private TextView textview5;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//设置属性textView.setText("OK");textview1.setText("OK1");textview2.setText("OK2");textview3.setText("OK3");textview4.setText("OK4");textview5.setText("OK5");} } 上面直接继承InjectActivity即可,文章上面也有说过:LayouyInject为什么作用域是TYPE,首先在加载view的时候,肯定是优先加载布局啊,ButterKnife也不例外。因此选择作用域在描述类,并且存在运行时。 二、解析Annotation原理 1、运行时 Annotation 解析 (1) 运行时 Annotation 指 @Retention 为 RUNTIME 的 Annotation,可手动调用下面常用 API 解析 method.getAnnotation(AnnotationName.class);method.getAnnotations();method.isAnnotationPresent(AnnotationName.class); 其他 @Target 如 Field,Class 方法类似 。 getAnnotation(AnnotationName.class) 表示得到该 Target 某个 Annotation 的信息,一个 Target 可以被多个 Annotation 修饰; getAnnotations() 则表示得到该 Target 所有 Annotation ; isAnnotationPresent(AnnotationName.class) 表示该 Target 是否被某个 Annotation 修饰; (2) 解析示例如下: public static void main(String[] args) {try {Class cls = Class.forName("cn.trinea.java.test.annotation.App");for (Method method : cls.getMethods()) {MethodInfo methodInfo = method.getAnnotation(MethodInfo.class);if (methodInfo != null) {System.out.println("method name:" + method.getName());System.out.println("method author:" + methodInfo.author());System.out.println("method version:" + methodInfo.version());System.out.println("method date:" + methodInfo.date());} }} catch (ClassNotFoundException e) {e.printStackTrace();} } 以之前自定义的 MethodInfo 为例,利用 Target(这里是 Method)getAnnotation 函数得到 Annotation 信息,然后就可以调用 Annotation 的方法得到响应属性值 。 2、编译时 Annotation 解析 (1) 编译时 Annotation 指 @Retention 为 CLASS 的 Annotation,甴 apt(Annotation Processing Tool) 解析自动解析。 使用方法: 自定义类集成自 AbstractProcessor; 重写其中的 process 函数 这块很多同学不理解,实际是 apt(Annotation Processing Tool) 在编译时自动查找所有继承自 AbstractProcessor 的类,然后调用他们的 process 方法去处理。 (2) 假设之前自定义的 MethodInfo 的 @Retention 为 CLASS,解析示例如下: @SupportedAnnotationTypes({ "cn.trinea.java.test.annotation.MethodInfo" })public class MethodInfoProcessor extends AbstractProcessor {@Overridepublic boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {HashMap<String, String> map = new HashMap<String, String>();for (TypeElement te : annotations) {for (Element element : env.getElementsAnnotatedWith(te)) {MethodInfo methodInfo = element.getAnnotation(MethodInfo.class);map.put(element.getEnclosingElement().toString(), methodInfo.author());} }return false;} } SupportedAnnotationTypes 表示这个 Processor 要处理的 Annotation 名字。 process 函数中参数 annotations 表示待处理的 Annotations,参数 env 表示当前或是之前的运行环境 process 函数返回值表示这组 annotations 是否被这个 Processor 接受,如果接受后续子的 rocessor 不会再对这个 Annotations 进行处理 三、几个 Android 开源库 Annotation 原理简析 1、Retrofit (1) 调用 @GET("/users/{username}")User getUser(@Path("username") String username); (2) 定义 @Documented@Target(METHOD)@Retention(RUNTIME)@RestMethod("GET")public @interface GET {String value();} 从定义可看出 Retrofit 的 Get Annotation 是运行时 Annotation,并且只能用于修饰 Method (3) 原理 private void parseMethodAnnotations() {for (Annotation methodAnnotation : method.getAnnotations()) {Class<? extends Annotation> annotationType = methodAnnotation.annotationType();RestMethod methodInfo = null;for (Annotation innerAnnotation : annotationType.getAnnotations()) {if (RestMethod.class == innerAnnotation.annotationType()) {methodInfo = (RestMethod) innerAnnotation;break;} }……} } RestMethodInfo.java 的 parseMethodAnnotations 方法如上,会检查每个方法的每个 Annotation, 看是否被 RestMethod 这个 Annotation 修饰的 Annotation 修饰,这个有点绕,就是是否被 GET、DELETE、POST、PUT、HEAD、PATCH 这些 Annotation 修饰,然后得到 Annotation 信息,在对接口进行动态代理时会掉用到这些 Annotation 信息从而完成调用。 因为 Retrofit 原理设计到动态代理,这里只介绍 Annotation。 2、Butter Knife (1) 调用 @InjectView(R.id.user) EditText username; (2) 定义 @Retention(CLASS) @Target(FIELD)public @interface InjectView {int value();} 可看出 Butter Knife 的 InjectView Annotation 是编译时 Annotation,并且只能用于修饰属性 (3) 原理 @Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {Map<TypeElement, ViewInjector> targetClassMap = findAndParseTargets(env);for (Map.Entry<TypeElement, ViewInjector> entry : targetClassMap.entrySet()) {TypeElement typeElement = entry.getKey();ViewInjector viewInjector = entry.getValue();try {JavaFileObject jfo = filer.createSourceFile(viewInjector.getFqcn(), typeElement);Writer writer = jfo.openWriter();writer.write(viewInjector.brewJava());writer.flush();writer.close();} catch (IOException e) {error(typeElement, "Unable to write injector for type %s: %s", typeElement, e.getMessage());} }return true;} ButterKnifeProcessor.java 的 process 方法如上,编译时,在此方法中过滤 InjectView 这个 Annotation 到 targetClassMap 后,会根据 targetClassMap 中元素生成不同的 class 文件到最终的 APK 中,然后在运行时调用 ButterKnife.inject(x) 函数时会到之前编译时生成的类中去找。 3、ActiveAndroid (1) 调用 @Column(name = “Name") public String name; (2) 定义 @Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface Column {……} 可看出 ActiveAndroid 的 Column Annotation 是运行时 Annotation,并且只能用于修饰属性 (3) 原理 Field idField = getIdField(type);mColumnNames.put(idField, mIdName);List<Field> fields = new LinkedList<Field>(ReflectionUtils.getDeclaredColumnFields(type));Collections.reverse(fields);for (Field field : fields) {if (field.isAnnotationPresent(Column.class)) {final Column columnAnnotation = field.getAnnotation(Column.class);String columnName = columnAnnotation.name();if (TextUtils.isEmpty(columnName)) {columnName = field.getName();}mColumnNames.put(field, columnName);} } TableInfo.java 的构造函数如上,运行时,得到所有行信息并存储起来用来构件表信息。 ———————————————————————— 最后一个问题,看看这段代码最后运行结果: public class Person {private int id;private String name;public Person(int id, String name) {this.id = id;this.name = name;}public boolean equals(Person person) {return person.id == id;}public int hashCode() {return id;}public static void main(String[] args) {Set<Person> set = new HashSet<Person>();for (int i = 0; i < 10; i++) {set.add(new Person(i, "Jim"));}System.out.println(set.size());} } 答案:示例代码运行结果应该是 10 而不是 1,这个示例代码程序实际想说明的是标记型注解 Override 的作用,为 equals 方法加上 Override 注解就知道 equals 方法的重载是错误的,参数不对。 本篇文章为转载内容。原文链接:https://blog.csdn.net/csdn_aiyang/article/details/81564408。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-28 22:30:35
104
转载
转载文章
...光标编辑的支持,配合特定快捷键,可在同一时间内对多个位置进行编辑,大大提升了代码编写速度。 总之,无论您是普通用户还是专业人员,持续关注系统更新动态并深入挖掘各类应用软件的快捷功能,都能助您在数字化工作中不断突破效率瓶颈,实现更加高效流畅的操作体验。
2023-02-01 13:38:26
91
转载
转载文章
...式事务解决方案 1、基于数据库XA协议的两段提交 XA协议是数据库支持的一种协议,其核心是一个事务管理器用来统一管理两个分布式数据库,如图 事务管理器负责跟支付宝数据库和余额宝数据库打交道,一旦有一个数据库连接失败,另一个数据库的操作就不会进行,一个数据库操作失败就会导致另一个数据库回滚,只有他们全部成功两个数据库的事务才会提交。 基于XA协议的两段和三段提交是一种严格的安全确认机制,其安全性是非常高的,但是保证安全性的前提是牺牲了性能,这个就是分布式系统里面的CAP理论,做任何架构的前提需要有取舍。所以基于XA协议的分布式事务并发性不高,不适合高并发场景。 2、基于activemq的解决方案 如图: 1、支付宝扣款成功时往message表插入消息 2、message表有message_id(流水id,标识夸系统的一次转账操作),status(confirm,unconfirm) 3、timer扫描message表的unconfirm状态记录往activemq插入消息 4、余额宝收到消息消费消息时先查询message表如果有记录就不处理如果没记录就进行数据库增款操作 5、如果余额宝数据库操作成功往余额宝message表插入消息,表字段跟支付宝message一致 6、如果5操作成功,回调支付宝接口修改message表状态,把unconfirm状态转换成confirm状态 问题描述: 1、支付宝设计message表的目的 如果支付宝往activemq插入消息而余额宝消费消息异常,有可能是消费消息成功而事务操作异常,有可能是网络异常等等不确定因素。如果出现异常而activemq收到了确认消息的信号,这时候activemq中的消息是删除了的,消息丢失了。设置message表就是有一个消息存根,activemq中消息丢失了message表中的消息还在。解决了activemq消息丢失问题 2、余额宝设计message表的目的 当余额宝消费成功并且数据库操作成功时,回调支付宝的消息确认接口,如果回调接口时出现异常导致支付宝状态修改失败还是unconfirm状态,这时候还会被timer扫描到,又会往activemq插入消息,又会被余额宝消费一边,但是这条消息已经消费成功了的只是回调失败而已,所以就需要有一个这样的message表,当余额宝消费时先插入message表,如果message根据message_id能查询到记录就说明之前这条消息被消费过就不再消费只需要回调成功即可,如果查询不到消息就消费这条消息继续数据库操作,数据库操作成功就往message表插入消息。 这样就解决了消息重复消费问题,这也是消费端的幂等操作。 基于消息中间件的分布式事务是最理想的分布式事务解决方案,兼顾了安全性和并发性! 接下来贴代码: 支付宝代码: @Controller@RequestMapping("/order")public class OrderController {/ @Description TODO @param @return 参数 @return String 返回类型 @throws userID:转账的用户ID amount:转多少钱/@Autowired@Qualifier("activemq")OrderService orderService;@RequestMapping("/transfer")public @ResponseBody String transferAmount(String userId,String messageId, int amount) {try {orderService.updateAmount(amount,messageId, userId);}catch (Exception e) {e.printStackTrace();return "===============================transferAmount failed===================";}return "===============================transferAmount successfull===================";}@RequestMapping("/callback")public String callback(String param) {JSONObject parse = JSONObject.parseObject(param);String respCode = parse.getString("respCode");if(!"OK".equalsIgnoreCase(respCode)) {return null;}try {orderService.updateMessage(param);}catch (Exception e) {e.printStackTrace();return "fail";}return "ok";} } public interface OrderService {public void updateAmount(int amount, String userId,String messageId);public void updateMessage(String param);} @Service("activemq")@Transactional(rollbackFor = Exception.class)public class OrderServiceActivemqImpl implements OrderService {Logger logger = LoggerFactory.getLogger(getClass());@AutowiredJdbcTemplate jdbcTemplate;@AutowiredJmsTemplate jmsTemplate;@Overridepublic void updateAmount(final int amount, final String messageId, final String userId) {String sql = "update account set amount = amount - ?,update_time=now() where user_id = ?";int count = jdbcTemplate.update(sql, new Object[]{amount, userId});if (count == 1) {//插入到消息记录表sql = "insert into message(user_id,message_id,amount,status) values (?,?,?,?)";int row = jdbcTemplate.update(sql,new Object[]{userId,messageId,amount,"unconfirm"});if(row == 1) {//往activemq中插入消息jmsTemplate.send("zg.jack.queue", new MessageCreator() {@Overridepublic Message createMessage(Session session) throws JMSException {com.zhuguang.jack.bean.Message message = new com.zhuguang.jack.bean.Message();message.setAmount(Integer.valueOf(amount));message.setStatus("unconfirm");message.setUserId(userId);message.setMessageId(messageId);return session.createObjectMessage(message);} });} }}@Overridepublic void updateMessage(String param) {JSONObject parse = JSONObject.parseObject(param);String messageId = parse.getString("messageId");String sql = "update message set status = ? where message_id = ?";int count = jdbcTemplate.update(sql,new Object[]{"confirm",messageId});if(count == 1) {logger.info(messageId + " callback successfull");} }} activemq.xml <?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:amq="http://activemq.apache.org/schema/core"xmlns:jms="http://www.springframework.org/schema/jms"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.1.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.1.xsdhttp://www.springframework.org/schema/jmshttp://www.springframework.org/schema/jms/spring-jms-4.1.xsdhttp://activemq.apache.org/schema/corehttp://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd"><context:component-scan base-package="com.zhuguang.jack" /><mvc:annotation-driven /><amq:connectionFactory id="amqConnectionFactory"brokerURL="tcp://192.168.88.131:61616"userName="system"password="manager" /><!-- 配置JMS连接工长 --><bean id="connectionFactory"class="org.springframework.jms.connection.CachingConnectionFactory"><constructor-arg ref="amqConnectionFactory" /><property name="sessionCacheSize" value="100" /></bean><!-- 定义消息队列(Queue) --><bean id="demoQueueDestination" class="org.apache.activemq.command.ActiveMQQueue"><!-- 设置消息队列的名字 --><constructor-arg><value>zg.jack.queue</value></constructor-arg></bean><!-- 配置JMS模板(Queue),Spring提供的JMS工具类,它发送、接收消息。 --><bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"><property name="connectionFactory" ref="connectionFactory" /><property name="defaultDestination" ref="demoQueueDestination" /><property name="receiveTimeout" value="10000" /><!-- true是topic,false是queue,默认是false,此处显示写出false --><property name="pubSubDomain" value="false" /></bean></beans> spring-dispatcher.xml <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:context="http://www.springframework.org/schema/context"xmlns:task="http://www.springframework.org/schema/task" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-3.2.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.2.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><!-- 引入同文件夹下的redis属性配置文件 --><!-- 解决springMVC响应数据乱码 text/plain就是响应的时候原样返回数据--><import resource="../activemq/activemq.xml"/><!--<context:property-placeholder ignore-unresolvable="true" location="classpath:config/core/core.properties,classpath:config/redis/redis-config.properties" />--><bean id="propertyConfigurerForProject1" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="order" value="1" /><property name="ignoreUnresolvablePlaceholders" value="true" /><property name="location"><value>classpath:config/core/core.properties</value></property></bean><mvc:annotation-driven><mvc:message-converters register-defaults="true"><bean class="org.springframework.http.converter.StringHttpMessageConverter"><property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" /></bean></mvc:message-converters></mvc:annotation-driven><!-- 避免IE执行AJAX时,返回JSON出现下载文件 --><bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value></list></property></bean><!-- 开启controller注解支持 --><!-- 注:如果base-package=com.avicit 则注解事务不起作用 TODO 读源码 --><context:component-scan base-package="com.zhuguang"></context:component-scan><mvc:view-controller path="/" view-name="redirect:/index" /><beanclass="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /><bean id="handlerAdapter"class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean><beanclass="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"><property name="mediaTypes"><map><entry key="json" value="application/json" /><entry key="xml" value="application/xml" /><entry key="html" value="text/html" /></map></property><property name="viewResolvers"><list><bean class="org.springframework.web.servlet.view.BeanNameViewResolver" /><bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"><property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /><property name="prefix" value="/" /><property name="suffix" value=".jsp" /></bean></list></property></bean><!-- 支持上传文件 --> <!-- 控制器异常处理 --><bean id="exceptionResolver"class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"><property name="exceptionMappings"><props><prop key="java.lang.Exception">error</prop></props></property></bean><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"><property name="driverClass"><value>${jdbc.driverClassName}</value></property><property name="jdbcUrl"><value>${jdbc.url}</value></property><property name="user"><value>${jdbc.username}</value></property><property name="password"><value>${jdbc.password}</value></property><property name="minPoolSize" value="10" /><property name="maxPoolSize" value="100" /><property name="maxIdleTime" value="1800" /><property name="acquireIncrement" value="3" /><property name="maxStatements" value="1000" /><property name="initialPoolSize" value="10" /><property name="idleConnectionTestPeriod" value="60" /><property name="acquireRetryAttempts" value="30" /><property name="breakAfterAcquireFailure" value="false" /><property name="testConnectionOnCheckout" value="false" /><property name="acquireRetryDelay"><value>100</value></property></bean><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /><aop:aspectj-autoproxy expose-proxy="true"/></beans> logback.xml <?xml version="1.0" encoding="UTF-8"?><!--scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒当scan为true时,此属性生效。默认的时间间隔为1分钟。debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。--><configuration scan="false" scanPeriod="60 seconds" debug="false"><!-- 定义日志的根目录 --><!-- <property name="LOG_HOME" value="/app/log" /> --><!-- 定义日志文件名称 --><property name="appName" value="netty"></property><!-- ch.qos.logback.core.ConsoleAppender 表示控制台输出 --><appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"><Encoding>UTF-8</Encoding><!--日志输出格式:%d表示日期时间,%thread表示线程名,%-5level:级别从左显示5个字符宽度%logger{50} 表示logger名字最长50个字符,否则按照句点分割。 %msg:日志消息,%n是换行符--><encoder><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern></encoder></appender><!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 --> <appender name="appLogAppender" class="ch.qos.logback.core.rolling.RollingFileAppender"><Encoding>UTF-8</Encoding><!-- 指定日志文件的名称 --> <file>${appName}.log</file><!--当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动。--><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><!--滚动时产生的文件的存放位置及文件名称 %d{yyyy-MM-dd}:按天进行日志滚动 %i:当文件大小超过maxFileSize时,按照i进行文件滚动--><fileNamePattern>${appName}-%d{yyyy-MM-dd}-%i.log</fileNamePattern><!-- 可选节点,控制保留的归档文件的最大数量,超出数量就删除旧文件。假设设置每天滚动,且maxHistory是365,则只保存最近365天的文件,删除之前的旧文件。注意,删除旧文件是,那些为了归档而创建的目录也会被删除。--><MaxHistory>365</MaxHistory><!-- 当日志文件超过maxFileSize指定的大小是,根据上面提到的%i进行日志文件滚动 注意此处配置SizeBasedTriggeringPolicy是无法实现按文件大小进行滚动的,必须配置timeBasedFileNamingAndTriggeringPolicy--><timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"><maxFileSize>100MB</maxFileSize></timeBasedFileNamingAndTriggeringPolicy></rollingPolicy><!--日志输出格式:%d表示日期时间,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %logger{50} 表示logger名字最长50个字符,否则按照句点分割。 %msg:日志消息,%n是换行符--> <encoder><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %-5level ] [ %logger{50} : %line ] - %msg%n</pattern></encoder></appender><!-- logger主要用于存放日志对象,也可以定义日志类型、级别name:表示匹配的logger类型前缀,也就是包的前半部分level:要记录的日志级别,包括 TRACE < DEBUG < INFO < WARN < ERRORadditivity:作用在于children-logger是否使用 rootLogger配置的appender进行输出,false:表示只用当前logger的appender-ref,true:表示当前logger的appender-ref和rootLogger的appender-ref都有效--><!-- <logger name="edu.hyh" level="info" additivity="true"><appender-ref ref="appLogAppender" /></logger> --><!-- root与logger是父子关系,没有特别定义则默认为root,任何一个类只会和一个logger对应,要么是定义的logger,要么是root,判断的关键在于找到这个logger,然后判断这个logger的appender和level。 --><root level="debug"><appender-ref ref="stdout" /><appender-ref ref="appLogAppender" /></root></configuration> 2、余额宝代码 package com.zhuguang.jack.controller;import com.alibaba.fastjson.JSONObject;import com.zhuguang.jack.service.OrderService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controller@RequestMapping("/order")public class OrderController {/ @Description TODO @param @return 参数 @return String 返回类型 @throws 模拟银行转账 userID:转账的用户ID amount:转多少钱/@AutowiredOrderService orderService;@RequestMapping("/transfer")public @ResponseBody String transferAmount(String userId, String amount) {try {orderService.updateAmount(Integer.valueOf(amount), userId);}catch (Exception e) {e.printStackTrace();return "===============================transferAmount failed===================";}return "===============================transferAmount successfull===================";} } 消息监听器 package com.zhuguang.jack.listener;import com.alibaba.fastjson.JSONObject;import com.zhuguang.jack.service.OrderService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.client.SimpleClientHttpRequestFactory;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.web.client.RestTemplate;import javax.jms.JMSException;import javax.jms.Message;import javax.jms.MessageListener;import javax.jms.ObjectMessage;@Service("queueMessageListener")public class QueueMessageListener implements MessageListener {private Logger logger = LoggerFactory.getLogger(getClass());@AutowiredOrderService orderService;@Transactional(rollbackFor = Exception.class)@Overridepublic void onMessage(Message message) {if (message instanceof ObjectMessage) {ObjectMessage objectMessage = (ObjectMessage) message;try {com.zhuguang.jack.bean.Message message1 = (com.zhuguang.jack.bean.Message) objectMessage.getObject();String userId = message1.getUserId();int count = orderService.queryMessageCountByUserId(userId);if (count == 0) {orderService.updateAmount(message1.getAmount(), message1.getUserId());orderService.insertMessage(message1.getUserId(), message1.getMessageId(), message1.getAmount(), "ok");} else {logger.info("异常转账");}RestTemplate restTemplate = createRestTemplate();JSONObject jo = new JSONObject();jo.put("messageId", message1.getMessageId());jo.put("respCode", "OK");String url = "http://jack.bank_a.com:8080/alipay/order/callback?param="+ jo.toJSONString();restTemplate.getForObject(url,null);} catch (JMSException e) {e.printStackTrace();throw new RuntimeException("异常");} }}public RestTemplate createRestTemplate() {SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();simpleClientHttpRequestFactory.setConnectTimeout(3000);simpleClientHttpRequestFactory.setReadTimeout(2000);return new RestTemplate(simpleClientHttpRequestFactory);} } package com.zhuguang.jack.service;public interface OrderService {public void updateAmount(int amount, String userId);public int queryMessageCountByUserId(String userId);public int insertMessage(String userId,String messageId,int amount,String status);} package com.zhuguang.jack.service;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.client.SimpleClientHttpRequestFactory;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.web.client.RestTemplate;@Service@Transactional(rollbackFor = Exception.class)public class OrderServiceImpl implements OrderService {private Logger logger = LoggerFactory.getLogger(getClass());@AutowiredJdbcTemplate jdbcTemplate;/ 更新数据库表,把账户余额减去amountd/@Overridepublic void updateAmount(int amount, String userId) {//1、农业银行转账3000,也就说农业银行jack账户要减3000String sql = "update account set amount = amount + ?,update_time=now() where user_id = ?";int count = jdbcTemplate.update(sql, new Object[] {amount, userId});if (count != 1) {throw new RuntimeException("订单创建失败,农业银行转账失败!");} }public RestTemplate createRestTemplate() {SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();simpleClientHttpRequestFactory.setConnectTimeout(3000);simpleClientHttpRequestFactory.setReadTimeout(2000);return new RestTemplate(simpleClientHttpRequestFactory);}@Overridepublic int queryMessageCountByUserId(String messageId) {String sql = "select count() from message where message_id = ?";int count = jdbcTemplate.queryForInt(sql, new Object[]{messageId});return count;}@Overridepublic int insertMessage(String userId, String message_id,int amount, String status) {String sql = "insert into message(user_id,message_id,amount,status) values(?,?,?)";int count = jdbcTemplate.update(sql, new Object[]{userId, message_id,amount, status});if(count == 1) {logger.info("Ok");}return count;} } activemq.xml <?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:amq="http://activemq.apache.org/schema/core"xmlns:jms="http://www.springframework.org/schema/jms"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.1.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.1.xsdhttp://www.springframework.org/schema/jmshttp://www.springframework.org/schema/jms/spring-jms-4.1.xsdhttp://activemq.apache.org/schema/corehttp://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd"><context:component-scan base-package="com.zhuguang.jack" /><mvc:annotation-driven /><amq:connectionFactory id="amqConnectionFactory"brokerURL="tcp://192.168.88.131:61616"userName="system"password="manager" /><!-- 配置JMS连接工长 --><bean id="connectionFactory"class="org.springframework.jms.connection.CachingConnectionFactory"><constructor-arg ref="amqConnectionFactory" /><property name="sessionCacheSize" value="100" /></bean><!-- 定义消息队列(Queue) --><bean id="demoQueueDestination" class="org.apache.activemq.command.ActiveMQQueue"><!-- 设置消息队列的名字 --><constructor-arg><value>zg.jack.queue</value></constructor-arg></bean><!-- 显示注入消息监听容器(Queue),配置连接工厂,监听的目标是demoQueueDestination,监听器是上面定义的监听器 --><bean id="queueListenerContainer"class="org.springframework.jms.listener.DefaultMessageListenerContainer"><property name="connectionFactory" ref="connectionFactory" /><property name="destination" ref="demoQueueDestination" /><property name="messageListener" ref="queueMessageListener" /></bean><!-- 配置JMS模板(Queue),Spring提供的JMS工具类,它发送、接收消息。 --><bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"><property name="connectionFactory" ref="connectionFactory" /><property name="defaultDestination" ref="demoQueueDestination" /><property name="receiveTimeout" value="10000" /><!-- true是topic,false是queue,默认是false,此处显示写出false --><property name="pubSubDomain" value="false" /></bean></beans> OK~~~~~~~~~~~~大功告成!!!, 如果大家觉得满意并且对技术感兴趣请加群:171239762, 纯技术交流群,非诚勿扰。 本篇文章为转载内容。原文链接:https://blog.csdn.net/luoyang_java/article/details/84953241。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-04-16 22:34:52
499
转载
转载文章
...一定的概率分布,即在特定情况下可能出现不同结果。在大脑思维过程中,这两种模型共同作用,反映了人类及其他生物思考的随机性和必然性,其中“灵魂”被比喻为旁观者,观察并体验着由概率机产生的各种心流状态。
2023-01-02 11:30:59
620
转载
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
env -i command
- 在干净的环境变量状态下执行命令。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"