前端技术
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
[用户输入本金与年利率的Java实现]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
转载文章
...72。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 AILAB专项训练 问题描述 编制程序完成下述任务:接受两个数,一个为用 户一年期定期存款金额,一个为按照百分比格式表示的利率;程序计算一年期满后本金与利息总额。说明:(1)存款金额以人民币元为单位,可能精确到分; (2)输入利率时不需要输入百分号,例如一年期定期存款年利率为2.52%,用户输入2.52即可;(3)按照国家法律,存款利息所得需缴纳20% 的所得税,计算结果时所得税部分应扣除。 输入格式 输入一行,包含两个实数,分别表示本金和年利率。 输出格式 输出一行,包含一个实数,保留到小数点后两位,表示一年后的本金与利息和。 样例输入 10000 2.52 样例输出 10201.60 import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);double a = sc.nextDouble();double b = sc.nextDouble();double res = a + a b / 100.0 0.8;System.out.printf("%.2f", res);} } 本篇文章为转载内容。原文链接:https://blog.csdn.net/Abdulaziz_Dev/article/details/123456172。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-11 18:55:39
90
转载
Java
..., Scanner是Java中用于接收用户输入的标准类,它提供了多种方法来读取不同数据类型(如整数、浮点数、字符串等)的输入。在程序运行时,通过创建Scanner对象并关联到System.in流,可以实现从键盘、文件或其他输入源获取用户输入的功能。 System.out.println() , 在Java编程语言中,System.out.println()是一个预定义的方法,属于java.io.PrintStream类的一部分,主要用于向控制台输出信息,并在输出内容后自动添加一个换行符。程序员可以通过该方法将变量值、字符串或者其他数据类型的表达式结果以可读的形式显示在控制台上,是Java中最常用的输出功能之一。 String.format() , String.format()是Java中的一个静态方法,属于String类,用于格式化并组合一组对象。它可以按照指定的格式规范生成一个新的字符串,类似于C语言中的printf函数。在处理输出时,String.format()允许程序员精确地控制输出内容的格式,比如对齐方式、整数和浮点数的小数位数以及如何插入变量值。例如,在文章中的应用场景中,String.format()被用来确保整数与字符串能够正确且美观地拼接在一起输出。
2023-12-24 11:21:23
397
数据库专家
转载文章
...96。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 1、时间与日期 ECMAScript 提供了 Date 类型来处理时间和日期。Date 类型内置一系列获取和设置日期时间信息的方法。 Date 类型 ECMAScript 中的 Date 类型是在早期 Java 中 java.util.Date 类基础上构建的。为此,Date 类型使用 UTC(Coordinated Universal Time,国际协调时间[又称世界统一时间])1970 年 1 月 1 日午夜(零时)开始经过的毫秒来保存日期。在使用这种数据存储格式的条件下,Date 类型保存的日期能够精确到 1970 年 1 月 1 日之前或之后的 285616 年。 创建一个日期对象,使用 new 运算符和 Date 构造方法(构造函数)即可。 var box = new Date(); // 创建一个日期对象 在调用 Date 构造方法而不传递参数的情况下,新建的对象自动获取当前的时间和日期。 alert(box); // 不同浏览器显示不同 ECMAScript 提供了两个方法,Date.parse()和 Date.UTC()。Date.parse()方法接收一个表示日期的字符串参数,然后尝试根据这个字符串返回相应的毫秒数。ECMA-262 没有定义 Date.parse()应该支持哪种日期格式,因此方法的行为因实现而异,因地区而异。默认通常接收的日期格式如下: ‘月/日/年’,如 6/13/2011; ‘英文月名 日, 年’,如 May 25, 2004; ‘英文星期几 英文月名 日 年 时:分:秒 时区’,如 Tue May 25 2004 00:00:00 GMT-070 alert(Date.parse('6/13/2011')); // 1307894400000 如果 Date.parse()没有传入或者不是标准的日期格式,那么就会返回 NaN。 alert(Date.parse()); // NaN 如果想输出指定的日期,那么把 Date.parse()传入 Date 构造方法里。 var box = new Date(Date.parse('6/13/2011')); // Mon Jun 13 2011 00:00:00 GMT+0800var box = new Date('6/13/2011'); // 直接传入,Date.parse()后台被调用 Date 对象及其在不同浏览器中的实现有许多奇怪的行为。其中有一种倾向是将超出的范围的值替换成当前的值,以便生成输出。例如,在解析“January 32, 2007”时,有的浏览器会将其解释为“February 1, 2007”。而 Opera 则倾向与插入当前月份的当前日期。 Date.UTC()方法同样也返回表示日期的毫秒数,但它与 Date.parse()在构建值时使用不同的信息。(年份,基于 0 的月份[0 表示 1 月,1 表示 2 月],月中的哪一天[1-31],小时数[0-23] ,分钟,秒以及毫秒)。只有前两个参数是必须的。如果没有提供月数,则天数为 1;如果省略其他参数,则统统为 0。 alert(Date.UTC(2011,11)); // 1322697600000 如果 Date.UTC()参数传递错误,那么就会出现负值或者 NaN 等非法信息。 alert(Date.UTC()); // 负值或者 NaN 如果要输出指定日期,那么直接把 Date.UTC()传入 Date 构造方法里即可。 var box = new Date(Date.UTC(2011,11, 5, 15, 13, 16)); 通用的方法 与其他类型一样,Date 类型也重写了 toLocaleString()、toString()和 valueOf()方法;但这些方法返回值与其他类型中的方法不同。 var box = new Date(Date.UTC(2011,11, 5, 15, 13, 16));alert('toString:' + box.toString());alert('toLocaleString:' + box.toLocaleString()); // 按本地格式输出 这两个方法在不同浏览器显示的效果又不一样,但不用担心,这两个方法只是在调试比较有用,在显示时间和日期上,没什么价值。valueOf()方法显示毫秒数。 日期格式化方法 Date 类型还有一些专门用于将日期格式化为字符串的方法。 var box = new Date();alert(box.toDateString()); // 以特定的格式显示星期几、月、日和年alert(box.toTimeString()); // 以特定的格式显示时、分、秒和时区alert(box.toLocaleDateString()); // 以特定地区格式显示星期几、月、日和年alert(box.toLocaleTimeString()); // 以特定地区格式显示时、分、秒和时区alert(box.toUTCString()); // 以特定的格式显示完整的 UTC 日期 组件方法 组件方法,是为我们单独获取你想要的各种时间/日期而提供的方法。需要注意的时候 ,这些方法中,有带 UTC 的,有不带 UTC 的。UTC 日期指的是在没有时区偏差的情况下的日期值。 alert(box.getTime()); // 获取日期的毫秒数,和 valueOf()返回一致alert(box.setTime(100)); // 以毫秒数设置日期,会改变整个日期alert(box.getFullYear()); // 获取四位年份alert(box.setFullYear(2012)); // 设置四位年份,返回的是毫秒数alert(box.getMonth()); // 获取月份,没指定月份,从 0 开始算起alert(box.setMonth(11)); // 设置月份alert(box.getDate()); // 获取日期alert(box.setDate(8)); // 设置日期,返回毫秒数alert(box.getDay()); // 返回星期几,0 表示星期日,6 表示星期六alert(box.setDay(2)); // 设置星期几alert(box.getHours()); // 返回时alert(box.setHours(12)); // 设置时alert(box.getMinutes()); // 返回分钟alert(box.setMinutes(22)); // 设置分钟alert(box.getSeconds()); // 返回秒数alert(box.setSeconds(44)); // 设置秒数alert(box.getMilliseconds()); // 返回毫秒数alert(box.setMilliseconds()); // 设置毫秒数alert(box.getTimezoneOffset()); // 返回本地时间和 UTC 时间相差的分钟数 以上方法除了 getTimezoneOffset(),其他都具有 UTC 功能,例如 setDate()及 getDate()获取星期几,那么就会有 setUTCDate()及getUTCDate(),表示世界协调时间。 2、正则表达式 假设用户需要在 HTML 表单中填写姓名、地址、出生日期等。那么在将表单提交到服务器进一步处理前,JavaScript 程序会检查表单以确认用户确实输入了信息并且这些信息是符合要求的。 什么是正则表达式 正则表达式(regular expression)是一个描述字符模式的对象。ECMAScript 的 RegExp 类表示正则表达式,而 String 和 RegExp 都定义了使用正则表达式进行强大的模式匹配和文本检索与替换的函数。 正则表达式主要用来验证客户端的输入数据。用户填写完表单单击按钮之后,表单就会被发送到服务器,在服务器端通常会用 PHP、ASP.NET 等服务器脚本对其进行进一步处理 。因为客户端验证,可以节约大量的服务器端的系统资源,并且提供更好的用户体验。 创建正则表达式 创建正则表达式和创建字符串类似,创建正则表达式提供了两种方法,一种是采用 new 运算符,另一个是采用字面量方式。 两种创建方式 var box = new RegExp('box'); // 第一个参数字符串var box = new RegExp('box', 'ig'); // 第二个参数可选模式修饰符 模式修饰符的可选参数 参数 含义 i 忽略大小写 g 全局匹配 m 多行匹配 var box = /box/; // 直接用两个反斜杠var box = /box/ig; // 在第二个斜杠后面加上模式修饰符 测试正则表达式 RegExp 对象包含两个方法:test()和 exec(),功能基本相似,用于测试字符串匹配。test()方法在字符串中查找是否存在指定的正则表达式并返回布尔值,如果存在则返回 true,不存在则返回 false。exec()方法也用于在字符串中查找指定正则表达式,如果 exec()方法执行成功,则返回包含该查找字符串的相关信息数组。如果执行失败,则返回 null。 RegExp 对象的方法 方法 功能 test 在字符串中测试模式匹配,返回 true 或 false exec 在字符串中执行匹配搜索,返回结果数组 // 使用 new 运算符的 test 方法示例var pattern = new RegExp('box', 'i'); // 创建正则模式,不区分大小写var str = 'This is a Box!'; // 创建要比对的字符串alert(pattern.test(str)); // 通过 test()方法验证是否匹配// 使用字面量方式的 test 方法示例var pattern = /box/i; // 创建正则模式,不区分大小写var str = 'This is a Box!';alert(pattern.test(str));// 使用一条语句实现正则匹配alert(/box/i.test('This is a Box!')); // 模式和字符串替换掉了两个变量// 使用 exec 返回匹配数组var pattern = /box/i;var str = 'This is a Box!';alert(pattern.exec(str)); // 匹配了返回数组,否则返回 null 使用字符串的正则表达式方法 除了 test()和 exec()方法,String 对象也提供了 4 个使用正则表达式的方法。 String 对象中的正则表达式方法 方法 含义 match(pattern) 返回 pattern 中的子串或 null replace(pattern, replacement) 用 replacement 替换 pattern search(pattern) 返回字符串中 pattern 开始位置 split(pattern) 返回字符串按指定 pattern 拆分的数组 // 使用 match 方法获取获取匹配数组var pattern = /box/ig; // 全局搜索var str = 'This is a Box!,That is a Box too';alert(str.match(pattern)); // 匹配到两个 Box,Boxalert(str.match(pattern).length); // 获取数组的长度// 使用 search 来查找匹配数据var pattern = /box/ig;var str = 'This is a Box!,That is a Box too';alert(str.search(pattern)); // 查找到返回位置,否则返回-1 因为 search 方法查找到即返回,也就是说无需 g 全局。 // 使用 replace 替换匹配到的数据var pattern = /box/ig;var str = 'This is a Box!,That is a Box too';alert(str.replace(pattern, 'Tom')); // 将 Box 替换成了 Tom// 使用 split 拆分成字符串数组var pattern = / /ig;var str = 'This is a Box!,That is a Box too';alert(str.split(pattern)); // 将空格拆开分组成数组 RegExp 对象的静态属性 属性 短名 含义 input $_ 当前被匹配的字符串 lastMatch $& 最后一个匹配字符串 lastParen $+ 最后一对圆括号内的匹配子串 leftContext $ 最后一次匹配前的子串 multiline $ 用于指定是否所有的表达式都用于多行的布尔值 rightContext $’ 在上次匹配之后的子串 // 使用静态属性var pattern = /(g)oogle/;var str = 'This is google!';pattern.test(str); // 执行一下alert(RegExp.input); // This is google!alert(RegExp.leftContext); // This isalert(RegExp.rightContext); // !alert(RegExp.lastMatch); // googlealert(RegExp.lastParen); // galert(RegExp.multiline); // false Opera 不支持 input、lastMatch、lastParen 和 multiline 属性。IE 不支持 multiline 属性。所有的属性可以使用短名来操作。RegExp.input 可以改写成 RegExp['$_'],依次类推。但 RegExp.input 比较特殊,它还可以写成 RegExp.$_。 RegExp 对象的实例属性 属性 含义 global Boolean 值,表示 g 是否已设置 ignoreCase Boolean 值,表示 i 是否已设置 lastIndex 整数,代表下次匹配将从哪里字符位置开始 multiline Boolean 值,表示 m 是否已设置 Source 正则表达式的源字符串形式 // 使用实例属性var pattern = /google/ig;alert(pattern.global); // true,是否全局了alert(pattern.ignoreCase); // true,是否忽略大小写alert(pattern.multiline); // false,是否支持换行alert(pattern.lastIndex); // 0,下次的匹配位置alert(pattern.source); // google,正则表达式的源字符串var pattern = /google/g;var str = 'google google google';pattern.test(str); // google,匹配第一次alert(pattern.lastIndex); // 6,第二次匹配的位 以上基本没什么用。并且 lastIndex 在获取下次匹配位置上 IE 和其他浏览器有偏差 ,主要表现在非全局匹配上。lastIndex 还支持手动设置,直接赋值操作。 获取控制 正则表达式元字符是包含特殊含义的字符。它们有一些特殊功能,可以控制匹配模式的方式。反斜杠后的元字符将失去其特殊含义。 字符类:单个字符和数字 元字符/元符号 匹配情况 . 匹配除换行符外的任意字符 [a-z0-9] 匹配括号中的字符集中的任意字符 [^a-z0-9] 匹配任意不在括号中的字符集中的字符 \d 匹配数字 \D 匹配非数字,同[^0-9]相同 \w 匹配字母和数字及_ \W 匹配非字母和数字及_ 字符类:空白字符 元字符/元符号 匹配情况 \0 匹配 null 字符 \b 匹配空格字符 \f 匹配进纸字符 \n 匹配换行符 \r 匹配回车字符 \t 匹配制表符 \s 匹配空白字符、空格、制表符和换行符 \S 匹配非空白字符 字符类:锚字符 元字符/元符号 匹配情况 ^ 行首匹配 $ 行尾匹配 \A 只有匹配字符串开始处 \b 匹配单词边界,词在[]内时无效 \B 匹配非单词边界 \G 匹配当前搜索的开始位置 \Z 匹配字符串结束处或行尾 \z 只匹配字符串结束处 字符类:重复字符 元字符/元符号 匹配情况 x? 匹配 0 个或 1 个 x x 匹配 0 个或任意多个 x x+ 匹配至少一个 x (xyz)+ 匹配至少一个(xyz) x{m,n} 匹配最少 m 个、最多 n 个 x 字符类:替代字符 元字符/元符号 匹配情况 this where 字符类:记录字符 元字符/元符号 匹配情况 (string) 用于反向引用的分组 \1 或$1 匹配第一个分组中的内容 \2 或$2 匹配第二个分组中的内容 \3 或$3 匹配第三个分组中的内容 // 使用点元字符var pattern = /g..gle/; // .匹配一个任意字符var str = 'google';alert(pattern.test(str));// 重复匹配var pattern = /g.gle/; // .匹配 0 个一个或多个var str = 'google'; //,?,+,{n,m}alert(pattern.test(str));// 使用字符类匹配var pattern = /g[a-zA-Z_]gle/; // [a-z]表示任意个 a-z 中的字符var str = 'google';alert(pattern.test(str));var pattern = /g[^0-9]gle/; // [^0-9]表示任意个非 0-9 的字符var str = 'google';alert(pattern.test(str));var pattern = /[a-z][A-Z]+/; // [A-Z]+表示 A-Z 一次或多次var str = 'gOOGLE';alert(pattern.test(str));// 使用元符号匹配var pattern = /g\wgle/; // \w匹配任意多个所有字母数字_var str = 'google';alert(pattern.test(str));var pattern = /google\d/; // \d匹配任意多个数字var str = 'google444';alert(pattern.test(str));var pattern = /\D{7,}/; // \D{7,}匹配至少 7 个非数字var str = 'google8';alert(pattern.test(str));// 使用锚元字符匹配var pattern = /^google$/; // ^从开头匹配,$从结尾开始匹配var str = 'google';alert(pattern.test(str));var pattern = /goo\sgle/; // \s 可以匹配到空格var str = 'goo gle';alert(pattern.test(str));var pattern = /google\b/; // \b 可以匹配是否到了边界var str = 'google';alert(pattern.test(str));// 使用或模式匹配var pattern = /google|baidu|bing/; // 匹配三种其中一种字符串var str = 'google';alert(pattern.test(str));// 使用分组模式匹配var pattern = /(google){4,8}/; // 匹配分组里的字符串 4-8 次var str = 'googlegoogle';alert(pattern.test(str));var pattern = /8(.)8/; // 获取 8..8 之间的任意字符var str = 'This is 8google8';str.match(pattern);alert(RegExp.$1); // 得到第一个分组里的字符串内容var pattern = /8(.)8/;var str = 'This is 8google8';var result = str.replace(pattern,'<strong>$1</strong>'); // 得到替换的字符串输出document.write(result);var pattern = /(.)\s(.)/;var str = 'google baidu';var result = str.replace(pattern, '$2 $1'); // 将两个分组的值替换输出document.write(result); 贪婪 惰性 + +? ? ?? ? {n} {n}? {n,} {n,}? {n,m} {n,m}? // 关于贪婪和惰性var pattern = /[a-z]+?/; // ?号关闭了贪婪匹配,只替换了第一个var str = 'abcdefjhijklmnopqrstuvwxyz';var result = str.replace(pattern, 'xxx');alert(result);var pattern = /8(.+?)8/g; // 禁止了贪婪,开启的全局var str = 'This is 8google8, That is 8google8, There is 8google8';var result = str.replace(pattern,'<strong>$1</strong>');document.write(result);var pattern = /8([^8])8/g; // 另一种禁止贪婪var str = 'This is 8google8, That is 8google8, There is 8google8';var result = str.replace(pattern,'<strong>$1</strong>');document.write(result);// 使用 exec 返回数组var pattern = /^[a-z]+\s[0-9]{4}$/i;var str = 'google 2012';alert(pattern.exec(str)); // 返回整个字符串var pattern = /^[a-z]+/i; // 只匹配字母var str = 'google 2012';alert(pattern.exec(str)); // 返回 googlevar pattern = /^([a-z]+)\s([0-9]{4})$/i; // 使用分组var str = 'google 2012';alert(pattern.exec(str)[0]); // google 2012alert(pattern.exec(str)[1]); // googlealert(pattern.exec(str)[2]); // 2012// 捕获性分组和非捕获性分组var pattern = /(\d+)([a-z])/; // 捕获性分组var str = '123abc';alert(pattern.exec(str));var pattern = /(\d+)(?:[a-z])/; // 非捕获性分组var str = '123abc';alert(pattern.exec(str));// 使用分组嵌套var pattern = /(A?(B?(C?)))/; // 从外往内获取var str = 'ABC';alert(pattern.exec(str));// 使用前瞻捕获var pattern = /(goo(?=gle))/; // goo 后面必须跟着 gle 才能捕获var str = 'google';alert(pattern.exec(str));// 使用特殊字符匹配var pattern = /\.\[\/b\]/; // 特殊字符,用\符号转义即可var str = '.[/b]';alert(pattern.test(str));// 使用换行模式var pattern = /^\d+/mg; // 启用了换行模式var str = '1.baidu\n2.google\n3.bing';var result = str.replace(pattern, '');alert(result); 常用的正则 检查邮政编码 var pattern = /[1-9][0-9]{5}/; // 共 6 位数字,第一位不能为 0var str = '224000';alert(pattern.test(str)); 检查文件压缩包 var pattern = /[\w]+\.zip|rar|gz/; // \w 表示所有数字和字母加下划线var str = '123.zip'; // \.表示匹配.,后面是一个选择alert(pattern.test(str)); 删除多余空格 var pattern = /\s/g; // g 必须全局,才能全部匹配var str = '111 222 333';var result = str.replace(pattern,''); // 把空格匹配成无空格alert(result); 删除首尾空格 var pattern = /^\s+/; // 强制首var str = ' goo gle ';var result = str.replace(pattern, '');pattern = /\s+$/; // 强制尾result = result.replace(pattern, '');alert('|' + result + '|');var pattern = /^\s(.+?)\s$/; // 使用了非贪婪捕获var str = ' google ';alert('|' + pattern.exec(str)[1] + '|');var pattern = /^\s(.+?)\s$/;var str = ' google ';alert('|' + str.replace(pattern, '$1') + '|'); // 使用了分组获取 简单的电子邮件验证 var pattern = /^([a-zA-Z0-9_\.\-]+)@([a-zA-Z0-9_\.\-]+)\.([a-zA-Z]{2,4})$/;var str = 'yc60.com@gmail.com';alert(pattern.test(str));var pattern = /^([\w\.\-]+)@([\w\.\-]+)\.([\w]{2,4})$/;var str = 'yc60.com@gmail.com';alert(pattern.test(str)); 3、Function类型 在 ECMAScript 中,Function(函数)类型实际上是对象。每个函数都是 Function 类型的实例,而且都与其他引用类型一样具有属性和方法。由于函数是对象,因此函数名实际上也是一个指向函数对象的指针。 函数的声明方式 普通的函数声明 function box(num1, num2) {return num1+ num2;} 使用变量初始化函数 var box= function(num1, num2) {return num1 + num2;}; 使用 Function 构造函数 var box= new Function('num1', 'num2' ,'return num1 + num2'); 第三种方式我们不推荐,因为这种语法会导致解析两次代码(第一次解析常规 ECMAScript 代码,第二次是解析传入构造函数中的字符串),从而影响性能。但我们可以通过这种语法来理解"函数是对象,函数名是指针"的概念。 作为值的函数 ECMAScript 中的函数名本身就是变量,所以函数也可以作为值来使用。也就是说,不仅可以像传递参数一样把一个函数传递给另一个函数,而且可以将一个函数作为另一个函数的结果返回。 function box(sumFunction, num) {return sumFunction(num); // someFunction}function sum(num) {return num + 10;}var result = box(sum, 10); // 传递函数到另一个函数里 函数内部属性 在函数内部,有两个特殊的对象:arguments 和 this。arguments 是一个类数组对象,包含着传入函数中的所有参数,主要用途是保存函数参数。但这个对象还有一个名叫 callee 的属性,该属性是一个指针,指向拥有这个 arguments 对象的函数。 function box(num) {if (num <= 1) {return 1;} else {return num box(num-1); // 一个简单的的递归} } 对于阶乘函数一般要用到递归算法,所以函数内部一定会调用自身;如果函数名不改变是没有问题的,但一旦改变函数名,内部的自身调用需要逐一修改。为了解决这个问题,我们可以使用 arguments.callee 来代替。 function box(num) {if (num <= 1) {return 1;} else {return num arguments.callee(num-1); // 使用 callee 来执行自身} } 函数内部另一个特殊对象是 this,其行为与 Java 和 C中的 this 大致相似。换句话说 ,this 引用的是函数据以执行操作的对象,或者说函数调用语句所处的那个作用域。当在全局作用域中调用函数时,this 对象引用的就是 window。 // 便于理解的改写例子window.color = '红色的'; // 全局的,或者 var color = '红色的';也行alert(this.color); // 打印全局的 colorvar box = {color : '蓝色的', // 局部的 colorsayColor : function () {alert(this.color); // 此时的 this 只能 box 里的 color} };box.sayColor(); // 打印局部的 coloralert(this.color); // 还是全局的// 引用教材的原版例子window.color = '红色的'; // 或者 var color = '红色的';也行var box = {color : '蓝色的'};function sayColor() {alert(this.color); // 这里第一次在外面,第二次在 box 里面}getColor();box.sayColor = sayColor; // 把函数复制到 box 对象里,成为了方法box.sayColor(); 函数属性和方法 ECMAScript 中的函数是对象,因此函数也有属性和方法。每个函数都包含两个属性 :length 和 prototype。其中,length 属性表示函数希望接收的命名参数的个数。 function box(name, age) {alert(name + age);}alert(box.length); // 2 对于 prototype 属性,它是保存所有实例方法的真正所在,也就是原型。这个属性 ,我们将在面向对象一章详细介绍。而 prototype 下有两个方法:apply()和 call(),每个函数都包含这两个非继承而来的方法。这两个方法的用途都在特定的作用域中调用函数,实际上等于设置函数体内 this 对象的值。 function box(num1, num2) {return num1 + num2; // 原函数}function sayBox(num1, num2) {return box.apply(this, [num1, num2]); // this 表示作用域,这里是 window} // []表示 box 所需要的参数function sayBox2(num1, num2) {return box.apply(this, arguments); // arguments 对象表示 box 所需要的参数}alert(sayBox(10,10)); // 20alert(sayBox2(10,10)); // 20 call()方法于 apply()方法相同,他们的区别仅仅在于接收参数的方式不同。对于 call()方法而言,第一个参数是作用域,没有变化,变化只是其余的参数都是直接传递给函数的。 function box(num1, num2) {return num1 + num2;}function callBox(num1, num2) {return box.call(this, num1, num2); // 和 apply 区别在于后面的传参}alert(callBox(10,10)); 事实上,传递参数并不是 apply()和 call()方法真正的用武之地;它们经常使用的地方是能够扩展函数赖以运行的作用域。 var color = '红色的'; // 或者 window.color = '红色的';也行var box = {color : '蓝色的'};function sayColor() {alert(this.color);}sayColor(); // 作用域在 windowsayColor.call(this); // 作用域在 windowsayColor.call(window); // 作用域在 windowsayColor.call(box); // 作用域在 box,对象冒充 这个例子是之前作用域理解的例子修改而成,我们可以发现当我们使用 call(box)方法的时候,sayColor()方法的运行环境已经变成了 box 对象里了。 使用 call()或者 apply()来扩充作用域的最大好处,就是对象不需要与方法发生任何耦合关系(耦合,就是互相关联的意思,扩展和维护会发生连锁反应)。也就是说,box 对象和 sayColor()方法之间不会有多余的关联操作,比如 box.sayColor = sayColor;。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gongxifacai_believe/article/details/108286196。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-24 13:01:25
529
转载
转载文章
...88。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 一、秒杀商品显示 1、使用生成器生成对应的表 记得在每个mapper类加入注解供spring扫描: @Repository 2、后端写得到秒杀商品的方法 ①、建实体类vo 用于连表查询,得到商品名字 package com.example.seckill.vo;import com.example.seckill.pojo.SeckillGoods;import lombok.Data;@Datapublic class SeckillGoodsVo extends SeckillGoods {private String goodsName;} ②、在SexkillGoodsMapper.xml文件中定义sql <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.seckill.mapper.SeckillGoodsMapper"><select id="queryAll" resultType="com.example.seckill.vo.SeckillGoodsVo">select sg.,g.goods_namefrom t_seckill_goods sg,t_goods gwhere sg.goods_id = g.gid;</select></mapper> ③、在mapper中定义 package com.example.seckill.mapper;import com.example.seckill.pojo.SeckillGoods;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.example.seckill.vo.SeckillGoodsVo;import org.springframework.stereotype.Repository;import java.util.List;/ <p> 秒杀商品信息表 Mapper 接口 </p> @author lv @since 2022-03-19/@Repositorypublic interface SeckillGoodsMapper extends BaseMapper<SeckillGoods> {List<SeckillGoodsVo> queryAll();} ④、service层与controller层 service: ISeckillGoodsService: package com.example.seckill.service;import com.example.seckill.pojo.SeckillGoods;import com.baomidou.mybatisplus.extension.service.IService;import com.example.seckill.util.response.ResponseResult;import com.example.seckill.vo.SeckillGoodsVo;import java.util.List;/ <p> 秒杀商品信息表 服务类 </p> @author lv @since 2022-03-19/public interface ISeckillGoodsService extends IService<SeckillGoods> {ResponseResult<List<SeckillGoodsVo>> queryAll();} SeckillGoodsServiceImpl: package com.example.seckill.service.impl;import com.example.seckill.pojo.SeckillGoods;import com.example.seckill.mapper.SeckillGoodsMapper;import com.example.seckill.service.ISeckillGoodsService;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.example.seckill.util.response.ResponseResult;import com.example.seckill.vo.SeckillGoodsVo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;/ <p> 秒杀商品信息表 服务实现类 </p> @author lv @since 2022-03-19/@Servicepublic class SeckillGoodsServiceImpl extends ServiceImpl<SeckillGoodsMapper, SeckillGoods> implements ISeckillGoodsService {@Autowiredprivate SeckillGoodsMapper seckillGoodsMapper;@Overridepublic ResponseResult<List<SeckillGoodsVo>> queryAll() {List<SeckillGoodsVo> list= seckillGoodsMapper.queryAll();return ResponseResult.success(list);} } controller: SeckillGoodsController: package com.example.seckill.controller;import com.example.seckill.service.ISeckillGoodsService;import com.example.seckill.util.response.ResponseResult;import com.example.seckill.vo.SeckillGoodsVo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List;/ <p> 秒杀商品信息表 前端控制器 </p> @author lv @since 2022-03-19/@RestController@RequestMapping("/seckillGoods")public class SeckillGoodsController {@Autowiredprivate ISeckillGoodsService seckillGoodsService;@RequestMapping("/queryAll")public ResponseResult<List<SeckillGoodsVo>> queryAll(){return seckillGoodsService.queryAll();} } 得到秒杀商品数据: 3、前端显示数据 ①、编辑跳转秒杀界面 goodList.ftl: <!DOCTYPE html><html lang="en"><head><include "../common/head.ftl"><style>.layui-this{background: deepskyblue !important;}</style></head><body class="layui-container layui-bg-orange"><div class="layui-tab"><ul class="layui-tab-title"><li class="layui-this">普通商品</li><li>秒杀商品</li></ul><-- 普通商品--><div class="layui-tab-content"><div class="layui-tab-item layui-show"><div class="layui-form-item"><label class="layui-form-label">搜索栏</label><div class="layui-input-inline"><input type="text" id="normal_name" name="text" placeholder="请输入搜索内容" class="layui-input"></div><div class="layui-input-inline"><button class="layui-btn layui-btn-primary" id="normal_search">🔍</button><button class="layui-btn layui-btn-primary" id="normal_add">增加</button></div></div><table id="normal_goods" lay-filter="normal_goods"></table><script type="text/html" id="button_1"><a class="layui-btn layui-btn-xs" lay-event="normal_del">删除</a><a class="layui-btn layui-btn-xs" lay-event="normal_edit">编辑</a></script></div><--秒杀界面--><div class="layui-tab-item"><div class="layui-form-item"><label class="layui-form-label">搜索栏</label><div class="layui-input-inline"><input type="text" id="seckill_name" name="text" placeholder="请输入搜索内容" class="layui-input"></div><div class="layui-input-inline"><button class="layui-btn layui-btn-primary" id="seckill_search">🔍</button><button class="layui-btn layui-btn-primary" id="seckill_add">增加</button></div></div><table id="seckill_goods" lay-filter="seckill_goods"></table></div></div></div></div><--引入js--><script src="/static/asset/js/project/goodsList.js"></script></body></html> ②、获取数据 goodList.js: // 秒杀商品let seckill_table=table.render({elem: 'seckill_goods',height: 500,url: '/seckillGoods/queryAll' //数据接口,parseData(res){ //res 即为原始返回的数据return {"code": res.code===200?0:1, //解析接口状态"msg": res.message, //解析提示文本"count": res.total, //解析数据长度"data": res.data //解析数据列表};},cols: [[ //表头{field: 'id', title: '秒杀商品编号', width:80, sort: true},{field: 'goodsId', title: '商品名字id'},{field: 'seckillPrice', title: '秒杀价格'},{field: 'stockCount', title: '秒杀库存'},{field: 'startDate', title: '活动开始时间'},{field: 'endDate', title: '活动结束时间'},{field: 'goodsName', title: '商品名称'}]]}); 呈现界面: 二、秒杀商品添加 1、后端:接收前端添加秒杀商品的数据 ①、实体类vo:SeckillGoodsVo private List<Map<String,Object>> goods; 修改实体类时间的类型:SeckillGoods @ApiModelProperty("秒杀开始时间")@TableField("start_date")@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Timestamp startDate;@ApiModelProperty("秒杀结束时间")@TableField("end_date")@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Timestamp endDate; ②、mapper层:SeckillGoodsMapper int addGoods(SeckillGoodsVo seckillGoodsVo); ③、mapper.xml层:SeckillGoodsMapper 批量插入秒杀商品的sql语句: <insert id="addGoods">insert into t_seckill_goods(goods_id, seckill_price, stock_count, start_date, end_date)values<foreach collection="goods" item="g" separator=",">({g.gid},{g.goodsPrice},{g.goodsStock},{startDate},{endDate})</foreach></insert> ④、service层 ISeckillGoodsService: ResponseResult<List<SeckillGoodsVo>> addGoods(SeckillGoodsVo seckillGoodsVo); SeckillGoodsServiceImpl: @Overridepublic ResponseResult<List<SeckillGoodsVo>> addGoods(SeckillGoodsVo seckillGoodsVo) {int goods=seckillGoodsMapper.addGoods(seckillGoodsVo);return ResponseResult.success(goods);} ⑤、controller层 @RequestMapping("/add")public ResponseResult<List<SeckillGoodsVo>> add(@RequestBody SeckillGoodsVo seckillGoodsVo){return seckillGoodsService.addGoods(seckillGoodsVo);} 2、前端 ①、定义数据与刷新、添加 goodsList.js: var layer,row,seckill_table// 添加秒杀商品$("seckill_add").click(()=>{layer.open({type:2,content: '/goods/SeckillGoodsOperate',area: ['800px','600px']})})// 秒杀商品刷新var seckill_reload = ()=> {seckill_table.reload({page:{curr:1 //current} });} var layer,row,seckill_tablelayui.define(()=>{let table=layui.tablelayer=layui.layerlet $=layui.jquerylet normal_table=table.render({elem: 'normal_goods',height: 500,url: '/goods/queryAll' //数据接口,page: true //开启分页,parseData(res){ //res 即为原始返回的数据return {"code": res.code===200?0:1, //解析接口状态"msg": res.message, //解析提示文本"count": res.total, //解析数据长度"data": res.data //解析数据列表};},//用于对分页请求的参数:page、limit重新设定名称request: {pageName: 'page' //页码的参数名称,默认:page,limitName: 'rows' //每页数据量的参数名,默认:limit},cols: [[ //表头{field: 'gid', title: '商品编号', width:80, sort: true, fixed: 'left'},{field: 'goodsName', title: '商品名字'},{field: 'goodsTitle', title: '商品标题'},{field: 'goodsImg',title: '商品图片',width:200,templet: (goods) => <b onmouseover='showImg("${goods.goodsImg}",this)'> + goods.goodsImg + </b> },{field: 'goodsDetail', title: '商品详情'},{field: 'goodsPrice', title: '商品价格', sort: true},{field: 'goodsStock', title: '商品库存', sort: true},{field: 'operate', title: '商品操作',toolbar: 'button_1'}]]});// 刷新表格let reloadTable=()=>{let goodsName=$("normal_value").val()// 【JS】自动化渲染的重载,重载表格normal_table.reload({where: {//设定异步数据接口的额外参数,height: 300goodsName},page:{curr:1 //current} });}// 搜索$("normal_search").click(reloadTable)// 增加$("normal_add").click(()=>{row = nullopenDialog()})//工具条事件table.on('tool(normal_goods)', function(obj) { //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"let data = obj.data; //获得当前行数据let layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)let tr = obj.tr; //获得当前行 tr 的 DOM 对象(如果有的话)if (layEvent === 'normal_del') { //删除row = data//获得当前行的数据let url="/goods/del/"+data.gidlayer.confirm('确定删除吗?',{title:'删除'}, function(index){//向服务端发送删除指令og$.getJSON(url,{gid:data.gid}, function(ret){layer.close(index);//关闭弹窗reloadTable()});layer.close(index);//关闭弹窗});}if (layEvent === 'normal_edit') { //编辑row = dataopenDialog()} })// 页面弹出let openDialog=()=>{// 如果是iframe层layer.open({type: 2,content: '/goods/goodsOperate', //这里content是一个URL,如果你不想让iframe出现滚动条,你还可以content: ['http://sentsin.com', 'no']area:['800px','600px'],btn: ['确定','取消'],yes(index,layero){let url="/goods/insert"// 拿到表格数据let data=$(layero).find("iframe")[0].contentWindow.getFormData()if(row) {url="/goods/edit"}$.ajax({url,data,datatype: "json",success(res){layer.closeAll()reloadTable()layer.msg(res.message)} })} });}// -------------------------秒杀商品-------------------------------------------seckill_table=table.render({elem: 'seckill_goods',height: 500,url: '/seckillGoods/queryAll' //数据接口,parseData(res){ //res 即为原始返回的数据return {"code": res.code===200?0:1, //解析接口状态"msg": res.message, //解析提示文本"count": res.total, //解析数据长度"data": res.data //解析数据列表};},cols: [[ //表头{field: 'id', title: '秒杀商品编号', width:80, sort: true},{field: 'goodsId', title: '商品名字id'},{field: 'seckillPrice', title: '秒杀价格'},{field: 'stockCount', title: '秒杀库存'},{field: 'startDate', title: '活动开始时间'},{field: 'endDate', title: '活动结束时间'},{field: 'goodsName', title: '商品名称'}]]});// 添加秒杀商品$("seckill_add").click(()=>{layer.open({type:2,content: '/goods/SeckillGoodsOperate',area: ['800px','600px']})})})// 图片显示let showImg = (src,obj)=> {layer.tips(<img src="${src}" width="100px">, obj);}// 秒杀商品刷新var seckill_reload = ()=> {seckill_table.reload({page:{curr:1 //current} });} ②、增加秒杀商品弹出页面样式 <!DOCTYPE html><html lang="en"><head><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><link rel="stylesheet" href="/static/asset/js/layui/css/layui.css" media="all"></head><body><div style="padding:15px 0px;"><div class="layui-condition"><form id="fm" name="fm" action="/" method="post" class="layui-form"><div class="layui-form-item"><div class="layui-inline"><label class="layui-form-label" style="width: 100px;text-align: left;">秒杀活动时间:</label><div class="layui-input-inline" style="width:280px;"><input type="text" class="layui-input" id="dt"></div><div class="layui-input-inline"><button class="layui-btn" id="btn_save" type="button"><i class="fa fa-search fa-right"></i>保 存</button></div></div></div></form></div><div class="layui-fluid" style="margin-top:-18px;"><table id="tb_goods" class="layui-table" lay-filter="tb_goods" style="margin-top:-5px;"></table></div></div><script src="/static/asset/js/layui/layui.js"></script><script src="/static/asset/js/project/seckillGoodsOperate.js"></script></body></html> ③、实现增加秒杀商品 seckillGoodsOperate.js: layui.define(()=>{let table=layui.tablelet laydate = layui.laydatelet $=layui.jquerylet layer=layui.layer// 读取普通商品table.render({elem: 'tb_goods',height: 500,url: '/goods/queryAll' //数据接口,page: true //开启分页,parseData(res){ //res 即为原始返回的数据return {"code": res.code===200?0:1, //解析接口状态"msg": res.message, //解析提示文本"count": res.total, //解析数据长度"data": res.data //解析数据列表};},//用于对分页请求的参数:page、limit重新设定名称request: {pageName: 'page' //页码的参数名称,默认:page,limitName: 'rows' //每页数据量的参数名,默认:limit},cols: [[ //表头// 全选按钮{field: '', type:"checkbox"},{field: 'gid', title: '商品编号', width:80},{field: 'goodsName', title: '商品名字'},{field: 'goodsTitle', title: '商品标题'},{field: 'goodsDetail', title: '商品详情'},{field: 'goodsPrice', title: '商品价格', sort: true},{field: 'goodsStock', title: '商品库存', sort: true}]]});// 构建时间选择器//执行一个laydate实例laydate.render({elem: 'dt', //指定元素type: "datetime",range: "~"});$("btn_save").click(()=>{// 获取时间let val=$("dt").val()if(!val){layer.msg("请选择时间")return}// 解析时间2022-2-2 ~2022-5-2let startDate=new Date(val.split("~")[0]).getTime()let endDate=new Date(val.split("~")[1]).getTime()// 获得选中的普通商品,获取选中行的数据let rows= table.checkStatus('tb_goods').data; //idTest 即为基础参数 id 对应的值if(!rows||rows.length===0){layer.msg("请选择数据")return}layer.prompt(function(value, index, elem){// 修改每个商品的数量rows.forEach(e=>{e.goodsStock=value})let data={startDate,endDate,goods:rows}// 访问后台的秒杀商品的接口$.ajax({url: "/seckillGoods/add",contentType:'application/json',data: JSON.stringify(data),datatype:"json",//返回类型type:"post",success(res){parent.seckill_reload()layer.closeAll()parent.layer.closeAll()layer.msg(res.message)} })});})}) ④、展示结果 增加成功: 三、秒杀商品的操作 1、后端操作秒杀单个商品详情 ①、mapper层 SeckillGoodsMapper: Map<String,Object> querySeckillGoodsById(Long id); mapper.xml文件:SeckillGoodsMapper.xml <select id="querySeckillGoodsById" resultType="map">select sg.id,sg.goods_id,sg.seckill_price,sg.stock_count,sg.start_date,sg.end_date,g.goods_img,g.goods_title,g.goods_detail,g.goods_name,(casewhen current_timestamp < sg.start_date then 0when (current_timestamp between sg.start_date and sg.end_date) then 1when current_timestamp > sg.end_date then 2end) goods_statusfrom t_goods g,t_seckill_goods sgwhere g.gid = sg.goods_idand sg.id = {0}</select> ②、service层 ISeckillGoodsService: Map<String,Object> querySeckillGoodsById(Long id); SeckillGoodsServiceImpl: @Overridepublic Map<String, Object> querySeckillGoodsById(Long id) {return seckillGoodsMapper.querySeckillGoodsById(id);} ③、controller层:SeckillGoodsController package com.example.seckill.controller;import com.example.seckill.service.ISeckillGoodsService;import com.example.seckill.util.response.ResponseResult;import com.example.seckill.vo.SeckillGoodsVo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.;import org.springframework.web.servlet.ModelAndView;import java.util.List;/ <p> 秒杀商品信息表 前端控制器 </p> @author lv @since 2022-03-19/@Controller@RequestMapping("/seckillGoods")public class SeckillGoodsController {@Autowiredprivate ISeckillGoodsService seckillGoodsService;// 返回json@ResponseBody@RequestMapping("/queryAll")public ResponseResult<List<SeckillGoodsVo>> queryAll(){return seckillGoodsService.queryAll();}@ResponseBody@RequestMapping("/add")public ResponseResult<List<SeckillGoodsVo>> add(@RequestBody SeckillGoodsVo seckillGoodsVo){return seckillGoodsService.addGoods(seckillGoodsVo);}// 正常跳转界面@RequestMapping("/query/{id}")public ModelAndView querySeckillGoodsById(@PathVariable("id") Long id) {ModelAndView mv = new ModelAndView("/goods/goodsSeckill");mv.addObject("goods", seckillGoodsService.querySeckillGoodsById(id));return mv;} } 2、前端展示 ①、在goodsList.js增加列的操作 {field: '', title: '操作', width: 140,templet: function (d) {return <div><a class="layui-btn layui-btn-xs layui-btn-danger">删除</a><a href="/seckillGoods/query/${d.id}" class="layui-btn layui-btn-xs layui-btn-normal">秒杀</a></div>;} } ②、添加秒杀详情界面 :goodsSkill.ftl <!DOCTYPE html><html lang="en"><head><include "../common/head.ftl"/></head><body><table style="position: absolute;top:-10px;" class="layui-table" border="1" cellpadding="0" cellspacing="0"><tr><td style="width:120px;">商品图片</td><td><img src="${goods['goods_img']}" alt=""></td></tr><tr><td>商品名称</td><td>${goods['goods_name']}</td></tr><tr><td>商品标题</td><td>${goods['goods_title']}</td></tr><tr><td>商品价格</td><td>${goods['seckill_price']}</td></tr><tr><td>开始时间</td><td><div style="position: relative;${(goods['goods_status']==1)?string('top:10px;','')}">${goods['start_date']?string("yyyy-MM-dd HH:mm:ss")}-${goods['end_date']?string("yyyy-MM-dd HH:mm:ss")}<if goods['goods_status']==0>活动未开始<elseif goods['goods_status']==1>活动热卖中<div style="position:relative;top:-10px;float:right;"><input type="hidden" id="goodsId" value="${goods['goods_id']}" name="goodsId"/><button class="layui-btn" id="buy">立即抢购</button></div><else>活动已结束</if></div></td></tr></table><script src="/static/asset/js/project/goodsSeckill.js"></script></body></html> ③、实现:goodsSkill.js let layer, form, $;layui.define(() => {layer = layui.layerform = layui.form$ = layui.jquery$('buy').click(() => {$.ajax({url: '/seckillOrder/addOrder',data: {goodsId: $('goodsId').val()},dataType: 'json',type: 'post',async: false,success: function (rs) {if (rs.code === 200)layer.msg(rs.message)elselayer.msg(rs.message)} })});}) ④、展示效果 点击秒杀: 3、后端操作秒杀抢购功能 ①、导入雪花id工具包:SnowFlake package com.example.seckill.util;@SuppressWarnings("all")public class SnowFlake {/ 起始的时间戳/private final static long START_STMP = 1480166465631L;/ 每一部分占用的位数/private final static long SEQUENCE_BIT = 12; //序列号占用的位数private final static long MACHINE_BIT = 5; //机器标识占用的位数private final static long DATACENTER_BIT = 5;//数据中心占用的位数/ 每一部分的最大值/private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);/ 每一部分向左的位移/private final static long MACHINE_LEFT = SEQUENCE_BIT;private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;private long datacenterId; //数据中心private long machineId; //机器标识private long sequence = 0L; //序列号private long lastStmp = -1L;//上一次时间戳public SnowFlake(long datacenterId, long machineId) {if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");}if (machineId > MAX_MACHINE_NUM || machineId < 0) {throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");}this.datacenterId = datacenterId;this.machineId = machineId;}public static void main(String[] args) {SnowFlake snowFlake = new SnowFlake(2, 3);long start = System.currentTimeMillis();for (int i = 0; i < 1000000; i++) {System.out.println(snowFlake.nextId());}System.out.println(System.currentTimeMillis() - start);}/ 产生下一个ID @return/public synchronized long nextId() {long currStmp = getNewstmp();if (currStmp < lastStmp) {throw new RuntimeException("Clock moved backwards. Refusing to generate id");}if (currStmp == lastStmp) {//相同毫秒内,序列号自增sequence = (sequence + 1) & MAX_SEQUENCE;//同一毫秒的序列数已经达到最大if (sequence == 0L) {currStmp = getNextMill();} } else {//不同毫秒内,序列号置为0sequence = 0L;}lastStmp = currStmp;return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分| datacenterId << DATACENTER_LEFT //数据中心部分| machineId << MACHINE_LEFT //机器标识部分| sequence; //序列号部分}private long getNextMill() {long mill = getNewstmp();while (mill <= lastStmp) {mill = getNewstmp();}return mill;}private long getNewstmp() {return System.currentTimeMillis();} } ②、service层 ISeckillOrderService : package com.example.seckill.service;import com.example.seckill.pojo.SeckillOrder;import com.baomidou.mybatisplus.extension.service.IService;import com.example.seckill.pojo.User;import com.example.seckill.util.response.ResponseResult;/ <p> 秒杀订单信息表 服务类 </p> @author lv @since 2022-03-19/public interface ISeckillOrderService extends IService<SeckillOrder> {ResponseResult<?> addOrder(Long goodsId, User user);} SeckillOrderServiceImpl : package com.example.seckill.service.impl;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;import com.example.seckill.exception.BusinessException;import com.example.seckill.mapper.GoodsMapper;import com.example.seckill.mapper.OrderMapper;import com.example.seckill.mapper.SeckillGoodsMapper;import com.example.seckill.pojo.;import com.example.seckill.mapper.SeckillOrderMapper;import com.example.seckill.service.ISeckillOrderService;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.example.seckill.util.SnowFlake;import com.example.seckill.util.response.ResponseResult;import com.example.seckill.util.response.ResponseResultCode;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;/ <p> 秒杀订单信息表 服务实现类 </p> @author lv @since 2022-03-19/@Servicepublic class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements ISeckillOrderService {@Autowiredprivate SeckillGoodsMapper seckillGoodsMapper;@Autowiredprivate GoodsMapper goodsMapper;@Autowiredprivate OrderMapper orderMapper;@Transactional(rollbackFor = Exception.class)@Overridepublic ResponseResult<?> addOrder(Long goodsId, User user) {// 下单前判断库存数SeckillGoods goods = seckillGoodsMapper.selectOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goodsId));if (goods == null) {throw new BusinessException(ResponseResultCode.SECKILL_ORDER_ERROR);}if (goods.getStockCount() < 1) {throw new BusinessException(ResponseResultCode.SECKILL_ORDER_ERROR);}// 限购SeckillOrder one = this.getOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId()).eq("goods_id", goodsId));if (one != null) {throw new BusinessException(ResponseResultCode.SECKILL_ORDER_EXISTS_ERROR);}// 库存减一int i = seckillGoodsMapper.update(null, new UpdateWrapper<SeckillGoods>().eq("goods_id", goodsId).setSql("stock_count=stock_count-1"));// 根据商品编号查询对应的商品(拿名字)Goods goodsInfo = goodsMapper.selectOne(new QueryWrapper<Goods>().eq("gid", goodsId));// 生成订单//生成雪花idSnowFlake snowFlake = new SnowFlake(5, 9);long id = snowFlake.nextId();//生成对应的订单Order normalOrder = new Order();normalOrder.setOid(id);normalOrder.setUserId(user.getId());normalOrder.setGoodsId(goodsId);normalOrder.setGoodsName(goodsInfo.getGoodsName());normalOrder.setGoodsCount(1);normalOrder.setGoodsPrice(goods.getSeckillPrice());orderMapper.insert(normalOrder);//生成秒杀订单SeckillOrder seckillOrder = new SeckillOrder();seckillOrder.setUserId(user.getId());seckillOrder.setOrderId(normalOrder.getOid());seckillOrder.setGoodsId(goodsId);this.save(seckillOrder);return ResponseResult.success();} } ③、controller层 SeckillOrderController : package com.example.seckill.controller;import com.example.seckill.pojo.User;import com.example.seckill.service.ISeckillOrderService;import com.example.seckill.util.response.ResponseResult;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/ <p> 秒杀订单信息表 前端控制器 </p> @author lv @since 2022-03-19/@RestController@RequestMapping("/seckillOrder")public class SeckillOrderController {@Autowiredprivate ISeckillOrderService seckillOrderService;@RequestMapping("/addOrder")public ResponseResult<?> addOrder(Long goodsId, User user){return seckillOrderService.addOrder(goodsId,user);} } ④、呈现结果 限购次数: 本期内容结束,下期内容更完善!!!!!!!!!!!!!!!!!!!!!1 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_60389087/article/details/123601288。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-02-25 23:20:34
121
转载
转载文章
...41。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 Struts上传、下载功能结合 /20171105_shiyan_upanddown/src/nuc/sw/action/DocDownloadAction.java package nuc.sw.action;import java.io.InputStream;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class DocDownloadAction extends ActionSupport { private String downPath;//返回InputStream流方法public InputStream getInputStream() throws Exception{ downPath = new String(downPath.getBytes("ISO8859-1"),"utf-8");//默认从WebAPP根目录下取资源return ServletActionContext.getServletContext().getResourceAsStream(downPath);}public String getDownPath(){return downPath;}public void setDownPath(String downPath){this.downPath=downPath;}public String getDownloadFileName(){//downPath.subString是截取downPath的一部分String downFileName=downPath.substring(7);try{downFileName = new String(downFileName.getBytes("iso8859-1"),"utf-8");//downFileName=new String(downFileName.getBytes(),"utf-8");}catch(Exception e){e.printStackTrace();}return downFileName;}@Overridepublic String execute() throws Exception { return SUCCESS;} } /20171105_shiyan_upanddown/src/nuc/sw/action/DocUploadAction.java package nuc.sw.action;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Date;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class DocUploadAction extends ActionSupport {private String name;private File[] upload;private String[] uploadContentType;private String[] uploadFileName;private String savePath;private Date createTime;public String getName() {return name;}public void setName(String name) {this.name = name;}public File[] getUpload() {return upload;}public void setUpload(File[] upload) {this.upload = upload;}public String[] getUploadContentType() {return uploadContentType;}public void setUploadContentType(String[] uploadContentType) {this.uploadContentType = uploadContentType;}public String[] getUploadFileName() {return uploadFileName;}public void setUploadFileName(String[] uploadFileName) {this.uploadFileName = uploadFileName;}public String getSavePath() {return savePath;}public void setSavePath(String savePath) {this.savePath = savePath;}public Date getCreateTime(){ createTime=new Date();return createTime;}public static void copy(File source,File target){ InputStream inputStream=null;OutputStream outputStream=null;try{inputStream=new BufferedInputStream(new FileInputStream(source));outputStream=new BufferedOutputStream(new FileOutputStream(target));byte[] buffer=new byte[1024];int length=0;while((length=inputStream.read(buffer))>0){outputStream.write(buffer, 0, length);} }catch(Exception e){e.printStackTrace();}finally{if(null!=inputStream){try {inputStream.close();} catch (IOException e2) {e2.printStackTrace();} }if(null!=outputStream){try{outputStream.close();}catch(Exception e2){e2.printStackTrace();} }} }@Overridepublic String execute() throws Exception { for(int i=0;i<upload.length;i++){ String path=ServletActionContext.getServletContext().getRealPath(this.getSavePath())+"\\"+this.uploadFileName[i];File target=new File(path);copy(this.upload[i],target);}return SUCCESS;} } /20171105_shiyan_upanddown/src/nuc/sw/action/LoginAction.java package nuc.sw.action;import java.util.regex.Pattern;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;public class LoginAction extends ActionSupport {//属性驱动校验private String username;private String password;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}//手动检验@Overridepublic void validate() {// TODO Auto-generated method stub//进行数据校验,长度6~15位 if(username.trim().length()<6||username.trim().length()>15||username==null) {this.addFieldError("username", "用户名长度不合法!");}if(password.trim().length()<6||password.trim().length()>15||password==null) {this.addFieldError("password", "密码长度不合法!");} }//登陆业务逻辑public String loginMethod() {if(username.equals("chenghaoran")&&password.equals("12345678")) {ActionContext.getContext().getSession().put("user", username);return "loginOK";}else {this.addFieldError("err","用户名或密码不正确!");return "loginFail";} }//手动校验validateXxxpublic void validateLoginMethod() {//使用正则校验if(username==null||username.trim().equals("")) {this.addFieldError("username","用户名不能为空!");}else {if(!Pattern.matches("[a-zA-Z]{6,15}", username.trim())) {this.addFieldError("username", "用户名格式错误!");} }if(password==null||password.trim().equals("")) {this.addFieldError("password","密码不能为空!");}else {if(!Pattern.matches("\\d{6,15}", password.trim())) {this.addFieldError("password", "密码格式错误!");} }} } /20171105_shiyan_upanddown/src/nuc/sw/interceptor/LoginInterceptor.java package nuc.sw.interceptor;import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;public class LoginInterceptor extends AbstractInterceptor {@Overridepublic String intercept(ActionInvocation arg0) throws Exception {// TODO Auto-generated method stub//判断是否登陆,通过ActionContext访问SessionActionContext ac=arg0.getInvocationContext();String username=(String)ac.getSession().get("user");if(username!=null&&username.equals("chenghaoran")) {return arg0.invoke();//放行}else {((ActionSupport)arg0.getAction()).addActionError("请先登录!");return Action.LOGIN;} }} /20171105_shiyan_upanddown/src/struts.xml <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN""http://struts.apache.org/dtds/struts-2.1.7.dtd"><struts><constant name="struts.i18n.encoding" value="utf-8"/><package name="default" extends="struts-default"><interceptors><interceptor name="login" class="nuc.sw.interceptor.LoginInterceptor"></interceptor></interceptors> <action name="docUpload" class="nuc.sw.action.DocUploadAction"><!-- 使用fileUpload拦截器 --><interceptor-ref name="fileUpload"><!-- 指定允许上传的文件大小最大为50000字节 --><param name="maximumSize">50000</param></interceptor-ref><!-- 配置默认系统拦截器栈 --><interceptor-ref name="defaultStack"/><!-- param子元素配置了DocUploadAction类中savePath属性值为/upload --><param name="savePath">/upload</param><result>/showFile.jsp</result><!-- 指定input逻辑视图,即不符合上传要求,被fileUpload拦截器拦截后,返回的视图页面 --><result name="input">/uploadFile.jsp</result></action> <action name="docDownload" class="nuc.sw.action.DocDownloadAction"><!-- 指定结果类型为stream --><result type="stream"><!-- 指定下载文件的文件类型 text/plain表示纯文本 --><param name="contentType">application/msword,text/plain</param><!-- 指定下载文件的入口输入流 --><param name="inputName">inputStream</param><!-- 指定下载文件的处理方式与文件保存名 attachment表示以附件形式下载,也可以用inline表示内联即在浏览器中直接显示,默认值为inline --><param name="contentDisposition">attachment;filename="${downloadFileName}"</param><!-- 指定下载文件的缓冲区大小,默认为1024 --><param name="bufferSize">40960</param></result></action><action name="loginAction" class="nuc.sw.action.LoginAction" method="loginMethod"><result name="loginOK">/uploadFile.jsp</result><result name="loginFail">/login.jsp</result><result name="input">/login.jsp</result></action> </package></struts> /20171105_shiyan_upanddown/WebContent/login.jsp <%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>登录页</title><s:head/></head><body><s:actionerror/><s:fielderror fieldName="err"></s:fielderror><s:form action="loginAction" method="post"> <s:textfield label="用户名" name="username"></s:textfield><s:password label="密码" name="password"></s:password><s:submit value="登陆"></s:submit></s:form></body></html> /20171105_shiyan_upanddown/WebContent/showFile.jsp <%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>显示上传文档</title></head><body><center><font style="font-size:18px;color:red">上传者:<s:property value="name"/></font><table width="45%" cellpadding="0" cellspacing="0" border="1"><tr><th>文件名称</th><th>上传者</th><th>上传时间</th></tr><s:iterator value="uploadFileName" status="st" var="doc"><tr><td align="center"><a href="docDownload.action?downPath=upload/<s:property value="doc"/>"><s:property value="doc"/> </a></td><td align="center"><s:property value="name"/></td><td align="center"><s:date name="createTime" format="yyyy-MM-dd HH:mm:ss"/></td></tr></s:iterator></table></center></body></html> /20171105_shiyan_upanddown/WebContent/uploadFile.jsp <%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>多文件上传</title></head><body><center><s:form action="docUpload" method="post" enctype="multipart/form-data"><s:textfield name="name" label="姓名" size="20"/><s:file name="upload" label="选择文档" size="20"/><s:file name="upload" label="选择文档" size="20"/><s:file name="upload" label="选择文档" size="20"/><s:submit value="确认上传" align="center"/></s:form></center></body></html> 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_34101492/article/details/78811741。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-11-12 20:53:42
140
转载
转载文章
...34。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 Spark Streaming电商广告点击综合案例 需求分析和技术架构 广告点击系统实时分析 广告来自于广告或者移动App等,广告需要设定在具体的广告位,当用户点击广告的时候,一般都会通过ajax或Socket往后台发送日志数据,在这里我们是要做基于SparkStreaming做实时在线统计。那么数据就需要放进消息系统(Kafka)中,我们的Spark Streaming应用程序就会去Kafka中Pull数据过来进行计算和消费,并把计算后的数据放入到持久化系统中(MySQL) 广告点击系统实时分析的意义:因为可以在线实时的看见广告的投放效果,就为广告的更大规模的投入和调整打下了坚实的基础,从而为公司带来最大化的经济回报。 核心需求: 1、实时黑名单动态过滤出有效的用户广告点击行为:因为黑名单用户可能随时出现,所以需要动态更新; 2、在线计算广告点击流量; 3、Top3热门广告; 4、每个广告流量趋势; 5、广告点击用户的区域分布分析 6、最近一分钟的广告点击量; 7、整个广告点击Spark Streaming处理程序724小时运行; 数据格式: 时间、用户、广告、城市等 技术细节: 在线计算用户点击的次数分析,屏蔽IP等; 使用updateStateByKey或者mapWithState进行不同地区广告点击排名的计算; Spark Streaming+Spark SQL+Spark Core等综合分析数据; 使用Window类型的操作; 高可用和性能调优等等; 流量趋势,一般会结合DB等; Spark Core / /package com.tom.spark.SparkApps.sparkstreaming;import java.util.Date;import java.util.HashMap;import java.util.Map;import java.util.Properties;import java.util.Random;import kafka.javaapi.producer.Producer;import kafka.producer.KeyedMessage;import kafka.producer.ProducerConfig;/ 数据生成代码,Kafka Producer产生数据/public class MockAdClickedStat {/ @param args/public static void main(String[] args) {final Random random = new Random();final String[] provinces = new String[]{"Guangdong", "Zhejiang", "Jiangsu", "Fujian"};final Map<String, String[]> cities = new HashMap<String, String[]>();cities.put("Guangdong", new String[]{"Guangzhou", "Shenzhen", "Dongguan"});cities.put("Zhejiang", new String[]{"Hangzhou", "Wenzhou", "Ningbo"});cities.put("Jiangsu", new String[]{"Nanjing", "Suzhou", "Wuxi"});cities.put("Fujian", new String[]{"Fuzhou", "Xiamen", "Sanming"});final String[] ips = new String[] {"192.168.112.240","192.168.112.239","192.168.112.245","192.168.112.246","192.168.112.247","192.168.112.248","192.168.112.249","192.168.112.250","192.168.112.251","192.168.112.252","192.168.112.253","192.168.112.254",};/ Kafka相关的基本配置信息/Properties kafkaConf = new Properties();kafkaConf.put("serializer.class", "kafka.serializer.StringEncoder");kafkaConf.put("metadeta.broker.list", "Master:9092,Worker1:9092,Worker2:9092");ProducerConfig producerConfig = new ProducerConfig(kafkaConf);final Producer<Integer, String> producer = new Producer<Integer, String>(producerConfig);new Thread(new Runnable() {public void run() {while(true) {//在线处理广告点击流的基本数据格式:timestamp、ip、userID、adID、province、cityLong timestamp = new Date().getTime();String ip = ips[random.nextInt(12)]; //可以采用网络上免费提供的ip库int userID = random.nextInt(10000);int adID = random.nextInt(100);String province = provinces[random.nextInt(4)];String city = cities.get(province)[random.nextInt(3)];String clickedAd = timestamp + "\t" + ip + "\t" + userID + "\t" + adID + "\t" + province + "\t" + city;producer.send(new KeyedMessage<Integer, String>("AdClicked", clickedAd));try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }} }).start();} } package com.tom.spark.SparkApps.sparkstreaming;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.LinkedBlockingQueue;import kafka.serializer.StringDecoder;import org.apache.spark.SparkConf;import org.apache.spark.api.java.JavaPairRDD;import org.apache.spark.api.java.JavaRDD;import org.apache.spark.api.java.JavaSparkContext;import org.apache.spark.api.java.function.Function;import org.apache.spark.api.java.function.Function2;import org.apache.spark.api.java.function.PairFunction;import org.apache.spark.api.java.function.VoidFunction;import org.apache.spark.sql.DataFrame;import org.apache.spark.sql.Row;import org.apache.spark.sql.RowFactory;import org.apache.spark.sql.hive.HiveContext;import org.apache.spark.sql.types.DataTypes;import org.apache.spark.sql.types.StructType;import org.apache.spark.streaming.Durations;import org.apache.spark.streaming.api.java.JavaDStream;import org.apache.spark.streaming.api.java.JavaPairDStream;import org.apache.spark.streaming.api.java.JavaPairInputDStream;import org.apache.spark.streaming.api.java.JavaStreamingContext;import org.apache.spark.streaming.api.java.JavaStreamingContextFactory;import org.apache.spark.streaming.kafka.KafkaUtils;import com.google.common.base.Optional;import scala.Tuple2;/ 数据处理,Kafka消费者/public class AdClickedStreamingStats {/ @param args/public static void main(String[] args) {// TODO Auto-generated method stub//好处:1、checkpoint 2、工厂final SparkConf conf = new SparkConf().setAppName("SparkStreamingOnKafkaDirect").setMaster("hdfs://Master:7077/");final String checkpointDirectory = "hdfs://Master:9000/library/SparkStreaming/CheckPoint_Data";JavaStreamingContextFactory factory = new JavaStreamingContextFactory() {public JavaStreamingContext create() {// TODO Auto-generated method stubreturn createContext(checkpointDirectory, conf);} };/ 可以从失败中恢复Driver,不过还需要指定Driver这个进程运行在Cluster,并且在提交应用程序的时候制定--supervise;/JavaStreamingContext javassc = JavaStreamingContext.getOrCreate(checkpointDirectory, factory);/ 第三步:创建Spark Streaming输入数据来源input Stream: 1、数据输入来源可以基于File、HDFS、Flume、Kafka、Socket等 2、在这里我们指定数据来源于网络Socket端口,Spark Streaming连接上该端口并在运行的时候一直监听该端口的数据 (当然该端口服务首先必须存在),并且在后续会根据业务需要不断有数据产生(当然对于Spark Streaming 应用程序的运行而言,有无数据其处理流程都是一样的) 3、如果经常在每间隔5秒钟没有数据的话不断启动空的Job其实会造成调度资源的浪费,因为并没有数据需要发生计算;所以 实际的企业级生成环境的代码在具体提交Job前会判断是否有数据,如果没有的话就不再提交Job;///创建Kafka元数据来让Spark Streaming这个Kafka Consumer利用Map<String, String> kafkaParameters = new HashMap<String, String>();kafkaParameters.put("metadata.broker.list", "Master:9092,Worker1:9092,Worker2:9092");Set<String> topics = new HashSet<String>();topics.add("SparkStreamingDirected");JavaPairInputDStream<String, String> adClickedStreaming = KafkaUtils.createDirectStream(javassc, String.class, String.class, StringDecoder.class, StringDecoder.class,kafkaParameters, topics);/因为要对黑名单进行过滤,而数据是在RDD中的,所以必然使用transform这个函数; 但是在这里我们必须使用transformToPair,原因是读取进来的Kafka的数据是Pair<String,String>类型, 另一个原因是过滤后的数据要进行进一步处理,所以必须是读进的Kafka数据的原始类型 在此再次说明,每个Batch Duration中实际上讲输入的数据就是被一个且仅被一个RDD封装的,你可以有多个 InputDStream,但其实在产生job的时候,这些不同的InputDStream在Batch Duration中就相当于Spark基于HDFS 数据操作的不同文件来源而已罢了。/JavaPairDStream<String, String> filteredadClickedStreaming = adClickedStreaming.transformToPair(new Function<JavaPairRDD<String,String>, JavaPairRDD<String,String>>() {public JavaPairRDD<String, String> call(JavaPairRDD<String, String> rdd) throws Exception {/ 在线黑名单过滤思路步骤: 1、从数据库中获取黑名单转换成RDD,即新的RDD实例封装黑名单数据; 2、然后把代表黑名单的RDD的实例和Batch Duration产生的RDD进行Join操作, 准确的说是进行leftOuterJoin操作,也就是说使用Batch Duration产生的RDD和代表黑名单的RDD实例进行 leftOuterJoin操作,如果两者都有内容的话,就会是true,否则的话就是false 我们要留下的是leftOuterJoin结果为false; /final List<String> blackListNames = new ArrayList<String>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();jdbcWrapper.doQuery("SELECT FROM blacklisttable", null, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {while(result.next()){blackListNames.add(result.getString(1));} }});List<Tuple2<String, Boolean>> blackListTuple = new ArrayList<Tuple2<String,Boolean>>();for(String name : blackListNames) {blackListTuple.add(new Tuple2<String, Boolean>(name, true));}List<Tuple2<String, Boolean>> blacklistFromListDB = blackListTuple; //数据来自于查询的黑名单表并且映射成为<String, Boolean>JavaSparkContext jsc = new JavaSparkContext(rdd.context());/ 黑名单的表中只有userID,但是如果要进行join操作的话就必须是Key-Value,所以在这里我们需要 基于数据表中的数据产生Key-Value类型的数据集合/JavaPairRDD<String, Boolean> blackListRDD = jsc.parallelizePairs(blacklistFromListDB);/ 进行操作的时候肯定是基于userID进行join,所以必须把传入的rdd进行mapToPair操作转化成为符合格式的RDD/JavaPairRDD<String, Tuple2<String, String>> rdd2Pair = rdd.mapToPair(new PairFunction<Tuple2<String,String>, String, Tuple2<String, String>>() {public Tuple2<String, Tuple2<String, String>> call(Tuple2<String, String> t) throws Exception {// TODO Auto-generated method stubString userID = t._2.split("\t")[2];return new Tuple2<String, Tuple2<String,String>>(userID, t);} });JavaPairRDD<String, Tuple2<Tuple2<String, String>, Optional<Boolean>>> joined = rdd2Pair.leftOuterJoin(blackListRDD);JavaPairRDD<String, String> result = joined.filter(new Function<Tuple2<String,Tuple2<Tuple2<String,String>,Optional<Boolean>>>, Boolean>() {public Boolean call(Tuple2<String, Tuple2<Tuple2<String, String>, Optional<Boolean>>> tuple)throws Exception {// TODO Auto-generated method stubOptional<Boolean> optional = tuple._2._2;if(optional.isPresent() && optional.get()){return false;} else {return true;} }}).mapToPair(new PairFunction<Tuple2<String,Tuple2<Tuple2<String,String>,Optional<Boolean>>>, String, String>() {public Tuple2<String, String> call(Tuple2<String, Tuple2<Tuple2<String, String>, Optional<Boolean>>> t)throws Exception {// TODO Auto-generated method stubreturn t._2._1;} });return result;} });//广告点击的基本数据格式:timestamp、ip、userID、adID、province、cityJavaPairDStream<String, Long> pairs = filteredadClickedStreaming.mapToPair(new PairFunction<Tuple2<String,String>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, String> t) throws Exception {String[] splited=t._2.split("\t");String timestamp = splited[0]; //YYYY-MM-DDString ip = splited[1];String userID = splited[2];String adID = splited[3];String province = splited[4];String city = splited[5]; String clickedRecord = timestamp + "_" +ip + "_"+userID+"_"+adID+"_"+province +"_"+city;return new Tuple2<String, Long>(clickedRecord, 1L);} });/ 第4.3步:在单词实例计数为1基础上,统计每个单词在文件中出现的总次数/JavaPairDStream<String, Long> adClickedUsers= pairs.reduceByKey(new Function2<Long, Long, Long>() {public Long call(Long i1, Long i2) throws Exception{return i1 + i2;} });/判断有效的点击,复杂化的采用机器学习训练模型进行在线过滤 简单的根据ip判断1天不超过100次;也可以通过一个batch duration的点击次数判断是否非法广告点击,通过一个batch来判断是不完整的,还需要一天的数据也可以每一个小时来判断。/JavaPairDStream<String, Long> filterClickedBatch = adClickedUsers.filter(new Function<Tuple2<String,Long>, Boolean>() {public Boolean call(Tuple2<String, Long> v1) throws Exception {if (1 < v1._2){//更新一些黑名单的数据库表return false;} else { return true;} }});//filterClickedBatch.print();//写入数据库filterClickedBatch.foreachRDD(new Function<JavaPairRDD<String,Long>, Void>() {public Void call(JavaPairRDD<String, Long> rdd) throws Exception {rdd.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Long>>>() {public void call(Iterator<Tuple2<String, Long>> partition) throws Exception {//使用数据库连接池的高效读写数据库的方式将数据写入数据库mysql//例如一次插入 1000条 records,使用insertBatch 或 updateBatch//插入的用户数据信息:userID,adID,clickedCount,time//这里面有一个问题,可能出现两条记录的key是一样的,此时需要更新累加操作List<UserAdClicked> userAdClickedList = new ArrayList<UserAdClicked>();while(partition.hasNext()) {Tuple2<String, Long> record = partition.next();String[] splited = record._1.split("\t");UserAdClicked userClicked = new UserAdClicked();userClicked.setTimestamp(splited[0]);userClicked.setIp(splited[1]);userClicked.setUserID(splited[2]);userClicked.setAdID(splited[3]);userClicked.setProvince(splited[4]);userClicked.setCity(splited[5]);userAdClickedList.add(userClicked);}final List<UserAdClicked> inserting = new ArrayList<UserAdClicked>();final List<UserAdClicked> updating = new ArrayList<UserAdClicked>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();//表的字段timestamp、ip、userID、adID、province、city、clickedCountfor(final UserAdClicked clicked : userAdClickedList) {jdbcWrapper.doQuery("SELECT clickedCount FROM adclicked WHERE"+ " timestamp =? AND userID = ? AND adID = ?",new Object[]{clicked.getTimestamp(), clicked.getUserID(),clicked.getAdID()}, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {// TODO Auto-generated method stubif(result.next()) {long count = result.getLong(1);clicked.setClickedCount(count);updating.add(clicked);} else {inserting.add(clicked);clicked.setClickedCount(1L);} }});}//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(UserAdClicked insertRecord : inserting) {insertParametersList.add(new Object[] {insertRecord.getTimestamp(),insertRecord.getIp(),insertRecord.getUserID(),insertRecord.getAdID(),insertRecord.getProvince(),insertRecord.getCity(),insertRecord.getClickedCount()});}jdbcWrapper.doBatch("INSERT INTO adclicked VALUES(?, ?, ?, ?, ?, ?, ?)", insertParametersList);//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> updateParametersList = new ArrayList<Object[]>();for(UserAdClicked updateRecord : updating) {updateParametersList.add(new Object[] {updateRecord.getTimestamp(),updateRecord.getIp(),updateRecord.getUserID(),updateRecord.getAdID(),updateRecord.getProvince(),updateRecord.getCity(),updateRecord.getClickedCount() + 1});}jdbcWrapper.doBatch("UPDATE adclicked SET clickedCount = ? WHERE"+ " timestamp =? AND ip = ? AND userID = ? AND adID = ? "+ "AND province = ? AND city = ?", updateParametersList);} });return null;} });//再次过滤,从数据库中读取数据过滤黑名单JavaPairDStream<String, Long> blackListBasedOnHistory = filterClickedBatch.filter(new Function<Tuple2<String,Long>, Boolean>() {public Boolean call(Tuple2<String, Long> v1) throws Exception {//广告点击的基本数据格式:timestamp,ip,userID,adID,province,cityString[] splited = v1._1.split("\t"); //提取key值String date =splited[0];String userID =splited[2];String adID =splited[3];//查询一下数据库同一个用户同一个广告id点击量超过50次列入黑名单//接下来 根据date、userID、adID条件去查询用户点击广告的数据表,获得总的点击次数//这个时候基于点击次数判断是否属于黑名单点击int clickedCountTotalToday = 81 ;if (clickedCountTotalToday > 50) {return true;}else {return false ;} }});//map操作,找出用户的idJavaDStream<String> blackListuserIDBasedInBatchOnhistroy =blackListBasedOnHistory.map(new Function<Tuple2<String,Long>, String>() {public String call(Tuple2<String, Long> v1) throws Exception {// TODO Auto-generated method stubreturn v1._1.split("\t")[2];} });//有一个问题,数据可能重复,在一个partition里面重复,这个好办;//但多个partition不能保证一个用户重复,需要对黑名单的整个rdd进行去重操作。//rdd去重了,partition也就去重了,一石二鸟,一箭双雕// 找出了黑名单,下一步就写入黑名单数据库表中JavaDStream<String> blackListUniqueuserBasedInBatchOnhistroy = blackListuserIDBasedInBatchOnhistroy.transform(new Function<JavaRDD<String>, JavaRDD<String>>() {public JavaRDD<String> call(JavaRDD<String> rdd) throws Exception {// TODO Auto-generated method stubreturn rdd.distinct();} });// 下一步写入到数据表中blackListUniqueuserBasedInBatchOnhistroy.foreachRDD(new Function<JavaRDD<String>, Void>() {public Void call(JavaRDD<String> rdd) throws Exception {rdd.foreachPartition(new VoidFunction<Iterator<String>>() {public void call(Iterator<String> t) throws Exception {// TODO Auto-generated method stub//插入的用户信息可以只包含:useID//此时直接插入黑名单数据表即可。//写入数据库List<Object[]> blackList = new ArrayList<Object[]>();while(t.hasNext()) {blackList.add(new Object[]{t.next()});}JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();jdbcWrapper.doBatch("INSERT INTO blacklisttable values (?)", blackList);} });return null;} });/广告点击累计动态更新,每个updateStateByKey都会在Batch Duration的时间间隔的基础上进行广告点击次数的更新, 更新之后我们一般都会持久化到外部存储设备上,在这里我们存储到MySQL数据库中/JavaPairDStream<String, Long> updateStateByKeyDSteam = filteredadClickedStreaming.mapToPair(new PairFunction<Tuple2<String,String>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, String> t)throws Exception {String[] splited=t._2.split("\t");String timestamp = splited[0]; //YYYY-MM-DDString ip = splited[1];String userID = splited[2];String adID = splited[3];String province = splited[4];String city = splited[5]; String clickedRecord = timestamp + "_" +ip + "_"+userID+"_"+adID+"_"+province +"_"+city;return new Tuple2<String, Long>(clickedRecord, 1L);} }).updateStateByKey(new Function2<List<Long>, Optional<Long>, Optional<Long>>() {public Optional<Long> call(List<Long> v1, Optional<Long> v2)throws Exception {// v1:当前的Key在当前的Batch Duration中出现的次数的集合,例如{1,1,1,。。。,1}// v2:当前的Key在以前的Batch Duration中积累下来的结果;Long clickedTotalHistory = 0L; if(v2.isPresent()){clickedTotalHistory = v2.get();}for(Long one : v1) {clickedTotalHistory += one;}return Optional.of(clickedTotalHistory);} });updateStateByKeyDSteam.foreachRDD(new Function<JavaPairRDD<String,Long>, Void>() {public Void call(JavaPairRDD<String, Long> rdd) throws Exception {rdd.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Long>>>() {public void call(Iterator<Tuple2<String, Long>> partition) throws Exception {//使用数据库连接池的高效读写数据库的方式将数据写入数据库mysql//例如一次插入 1000条 records,使用insertBatch 或 updateBatch//插入的用户数据信息:timestamp、adID、province、city//这里面有一个问题,可能出现两条记录的key是一样的,此时需要更新累加操作List<AdClicked> AdClickedList = new ArrayList<AdClicked>();while(partition.hasNext()) {Tuple2<String, Long> record = partition.next();String[] splited = record._1.split("\t");AdClicked adClicked = new AdClicked();adClicked.setTimestamp(splited[0]);adClicked.setAdID(splited[1]);adClicked.setProvince(splited[2]);adClicked.setCity(splited[3]);adClicked.setClickedCount(record._2);AdClickedList.add(adClicked);}final List<AdClicked> inserting = new ArrayList<AdClicked>();final List<AdClicked> updating = new ArrayList<AdClicked>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();//表的字段timestamp、ip、userID、adID、province、city、clickedCountfor(final AdClicked clicked : AdClickedList) {jdbcWrapper.doQuery("SELECT clickedCount FROM adclickedcount WHERE"+ " timestamp = ? AND adID = ? AND province = ? AND city = ?",new Object[]{clicked.getTimestamp(), clicked.getAdID(),clicked.getProvince(), clicked.getCity()}, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {// TODO Auto-generated method stubif(result.next()) {long count = result.getLong(1);clicked.setClickedCount(count);updating.add(clicked);} else {inserting.add(clicked);clicked.setClickedCount(1L);} }});}//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(AdClicked insertRecord : inserting) {insertParametersList.add(new Object[] {insertRecord.getTimestamp(),insertRecord.getAdID(),insertRecord.getProvince(),insertRecord.getCity(),insertRecord.getClickedCount()});}jdbcWrapper.doBatch("INSERT INTO adclickedcount VALUES(?, ?, ?, ?, ?)", insertParametersList);//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> updateParametersList = new ArrayList<Object[]>();for(AdClicked updateRecord : updating) {updateParametersList.add(new Object[] {updateRecord.getClickedCount(),updateRecord.getTimestamp(),updateRecord.getAdID(),updateRecord.getProvince(),updateRecord.getCity()});}jdbcWrapper.doBatch("UPDATE adclickedcount SET clickedCount = ? WHERE"+ " timestamp =? AND adID = ? AND province = ? AND city = ?", updateParametersList);} });return null;} });/ 对广告点击进行TopN计算,计算出每天每个省份Top5排名的广告 因为我们直接对RDD进行操作,所以使用了transfomr算子;/updateStateByKeyDSteam.transform(new Function<JavaPairRDD<String,Long>, JavaRDD<Row>>() {public JavaRDD<Row> call(JavaPairRDD<String, Long> rdd) throws Exception {JavaRDD<Row> rowRDD = rdd.mapToPair(new PairFunction<Tuple2<String,Long>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, Long> t)throws Exception {// TODO Auto-generated method stubString[] splited=t._1.split("_");String timestamp = splited[0]; //YYYY-MM-DDString adID = splited[3];String province = splited[4];String clickedRecord = timestamp + "_" + adID + "_" + province;return new Tuple2<String, Long>(clickedRecord, t._2);} }).reduceByKey(new Function2<Long, Long, Long>() {public Long call(Long v1, Long v2) throws Exception {// TODO Auto-generated method stubreturn v1 + v2;} }).map(new Function<Tuple2<String,Long>, Row>() {public Row call(Tuple2<String, Long> v1) throws Exception {// TODO Auto-generated method stubString[] splited=v1._1.split("_");String timestamp = splited[0]; //YYYY-MM-DDString adID = splited[3];String province = splited[4];return RowFactory.create(timestamp, adID, province, v1._2);} });StructType structType = DataTypes.createStructType(Arrays.asList(DataTypes.createStructField("timestamp", DataTypes.StringType, true),DataTypes.createStructField("adID", DataTypes.StringType, true),DataTypes.createStructField("province", DataTypes.StringType, true),DataTypes.createStructField("clickedCount", DataTypes.LongType, true)));HiveContext hiveContext = new HiveContext(rdd.context());DataFrame df = hiveContext.createDataFrame(rowRDD, structType);df.registerTempTable("topNTableSource");DataFrame result = hiveContext.sql("SELECT timestamp, adID, province, clickedCount, FROM"+ " (SELECT timestamp, adID, province,clickedCount, "+ "ROW_NUMBER() OVER(PARTITION BY province ORDER BY clickeCount DESC) rank "+ "FROM topNTableSource) subquery "+ "WHERE rank <= 5");return result.toJavaRDD();} }).foreachRDD(new Function<JavaRDD<Row>, Void>() {public Void call(JavaRDD<Row> rdd) throws Exception {// TODO Auto-generated method stubrdd.foreachPartition(new VoidFunction<Iterator<Row>>() {public void call(Iterator<Row> t) throws Exception {// TODO Auto-generated method stubList<AdProvinceTopN> adProvinceTopN = new ArrayList<AdProvinceTopN>();while(t.hasNext()) {Row row = t.next();AdProvinceTopN item = new AdProvinceTopN();item.setTimestamp(row.getString(0));item.setAdID(row.getString(1));item.setProvince(row.getString(2));item.setClickedCount(row.getLong(3));adProvinceTopN.add(item);}// final List<AdProvinceTopN> inserting = new ArrayList<AdProvinceTopN>();// final List<AdProvinceTopN> updating = new ArrayList<AdProvinceTopN>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();Set<String> set = new HashSet<String>();for(AdProvinceTopN item: adProvinceTopN){set.add(item.getTimestamp() + "_" + item.getProvince());}//表的字段timestamp、adID、province、clickedCountArrayList<Object[]> deleteParametersList = new ArrayList<Object[]>();for(String deleteRecord : set) {String[] splited = deleteRecord.split("_");deleteParametersList.add(new Object[]{splited[0],splited[1]});}jdbcWrapper.doBatch("DELETE FROM adprovincetopn WHERE timestamp = ? AND province = ?", deleteParametersList);//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(AdProvinceTopN insertRecord : adProvinceTopN) {insertParametersList.add(new Object[] {insertRecord.getClickedCount(),insertRecord.getTimestamp(),insertRecord.getAdID(),insertRecord.getProvince()});}jdbcWrapper.doBatch("INSERT INTO adprovincetopn VALUES (?, ?, ?, ?)", insertParametersList);} });return null;} });/ 计算过去半个小时内广告点击的趋势 广告点击的基本数据格式:timestamp、ip、userID、adID、province、city/filteredadClickedStreaming.mapToPair(new PairFunction<Tuple2<String,String>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, String> t)throws Exception {String splited[] = t._2.split("\t");String adID = splited[3];String time = splited[0]; //Todo:后续需要重构代码实现时间戳和分钟的转换提取。此处需要提取出该广告的点击分钟单位return new Tuple2<String, Long>(time + "_" + adID, 1L);} }).reduceByKeyAndWindow(new Function2<Long, Long, Long>() {public Long call(Long v1, Long v2) throws Exception {// TODO Auto-generated method stubreturn v1 + v2;} }, new Function2<Long, Long, Long>() {public Long call(Long v1, Long v2) throws Exception {// TODO Auto-generated method stubreturn v1 - v2;} }, Durations.minutes(30), Durations.milliseconds(5)).foreachRDD(new Function<JavaPairRDD<String,Long>, Void>() {public Void call(JavaPairRDD<String, Long> rdd) throws Exception {// TODO Auto-generated method stubrdd.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Long>>>() {public void call(Iterator<Tuple2<String, Long>> partition)throws Exception {List<AdTrendStat> adTrend = new ArrayList<AdTrendStat>();// TODO Auto-generated method stubwhile(partition.hasNext()) {Tuple2<String, Long> record = partition.next();String[] splited = record._1.split("_");String time = splited[0];String adID = splited[1];Long clickedCount = record._2;/ 在插入数据到数据库的时候具体需要哪些字段?time、adID、clickedCount; 而我们通过J2EE技术进行趋势绘图的时候肯定是需要年、月、日、时、分这个维度的,所以我们在这里需要 年月日、小时、分钟这些时间维度;/AdTrendStat adTrendStat = new AdTrendStat();adTrendStat.setAdID(adID);adTrendStat.setClickedCount(clickedCount);adTrendStat.set_date(time); //Todo:获取年月日adTrendStat.set_hour(time); //Todo:获取小时adTrendStat.set_minute(time);//Todo:获取分钟adTrend.add(adTrendStat);}final List<AdTrendStat> inserting = new ArrayList<AdTrendStat>();final List<AdTrendStat> updating = new ArrayList<AdTrendStat>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();//表的字段timestamp、ip、userID、adID、province、city、clickedCountfor(final AdTrendStat trend : adTrend) {final AdTrendCountHistory adTrendhistory = new AdTrendCountHistory();jdbcWrapper.doQuery("SELECT clickedCount FROM adclickedtrend WHERE"+ " date =? AND hour = ? AND minute = ? AND AdID = ?",new Object[]{trend.get_date(), trend.get_hour(), trend.get_minute(),trend.getAdID()}, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {// TODO Auto-generated method stubif(result.next()) {long count = result.getLong(1);adTrendhistory.setClickedCountHistoryLong(count);updating.add(trend);} else { inserting.add(trend);} }});}//表的字段date、hour、minute、adID、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(AdTrendStat insertRecord : inserting) {insertParametersList.add(new Object[] {insertRecord.get_date(),insertRecord.get_hour(),insertRecord.get_minute(),insertRecord.getAdID(),insertRecord.getClickedCount()});}jdbcWrapper.doBatch("INSERT INTO adclickedtrend VALUES(?, ?, ?, ?, ?)", insertParametersList);//表的字段date、hour、minute、adID、clickedCountList<Object[]> updateParametersList = new ArrayList<Object[]>();for(AdTrendStat updateRecord : updating) {updateParametersList.add(new Object[] {updateRecord.getClickedCount(),updateRecord.get_date(),updateRecord.get_hour(),updateRecord.get_minute(),updateRecord.getAdID()});}jdbcWrapper.doBatch("UPDATE adclickedtrend SET clickedCount = ? WHERE"+ " date =? AND hour = ? AND minute = ? AND AdID = ?", updateParametersList);} });return null;} });;/ Spark Streaming 执行引擎也就是Driver开始运行,Driver启动的时候是位于一条新的线程中的,当然其内部有消息循环体,用于 接收应用程序本身或者Executor中的消息,/javassc.start();javassc.awaitTermination();javassc.close();}private static JavaStreamingContext createContext(String checkpointDirectory, SparkConf conf) {// If you do not see this printed, that means the StreamingContext has been loaded// from the new checkpointSystem.out.println("Creating new context");// Create the context with a 5 second batch sizeJavaStreamingContext ssc = new JavaStreamingContext(conf, Durations.seconds(10));ssc.checkpoint(checkpointDirectory);return ssc;} }class JDBCWrapper {private static JDBCWrapper jdbcInstance = null;private static LinkedBlockingQueue<Connection> dbConnectionPool = new LinkedBlockingQueue<Connection>();static {try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} }public static JDBCWrapper getJDBCInstance() {if(jdbcInstance == null) {synchronized (JDBCWrapper.class) {if(jdbcInstance == null) {jdbcInstance = new JDBCWrapper();} }}return jdbcInstance; }private JDBCWrapper() {for(int i = 0; i < 10; i++){try {Connection conn = DriverManager.getConnection("jdbc:mysql://Master:3306/sparkstreaming","root", "root");dbConnectionPool.put(conn);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} } }public synchronized Connection getConnection() {while(0 == dbConnectionPool.size()){try {Thread.sleep(20);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }return dbConnectionPool.poll();}public int[] doBatch(String sqlText, List<Object[]> paramsList){Connection conn = getConnection();PreparedStatement preparedStatement = null;int[] result = null;try {conn.setAutoCommit(false);preparedStatement = conn.prepareStatement(sqlText);for(Object[] parameters: paramsList) {for(int i = 0; i < parameters.length; i++){preparedStatement.setObject(i + 1, parameters[i]);} preparedStatement.addBatch();}result = preparedStatement.executeBatch();conn.commit();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if(preparedStatement != null) {try {preparedStatement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} }if(conn != null) {try {dbConnectionPool.put(conn);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }}return result; }public void doQuery(String sqlText, Object[] paramsList, ExecuteCallBack callback){Connection conn = getConnection();PreparedStatement preparedStatement = null;ResultSet result = null;try {preparedStatement = conn.prepareStatement(sqlText);for(int i = 0; i < paramsList.length; i++){preparedStatement.setObject(i + 1, paramsList[i]);} result = preparedStatement.executeQuery();try {callback.resultCallBack(result);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} } catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if(preparedStatement != null) {try {preparedStatement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} }if(conn != null) {try {dbConnectionPool.put(conn);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }} }}interface ExecuteCallBack {void resultCallBack(ResultSet result) throws Exception;}class UserAdClicked {private String timestamp;private String ip;private String userID;private String adID;private String province;private String city;private Long clickedCount;public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public String getUserID() {return userID;}public void setUserID(String userID) {this.userID = userID;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdClicked {private String timestamp;private String adID;private String province;private String city;private Long clickedCount;public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdProvinceTopN {private String timestamp;private String adID;private String province;private Long clickedCount;public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdTrendStat {private String _date;private String _hour;private String _minute;private String adID;private Long clickedCount;public String get_date() {return _date;}public void set_date(String _date) {this._date = _date;}public String get_hour() {return _hour;}public void set_hour(String _hour) {this._hour = _hour;}public String get_minute() {return _minute;}public void set_minute(String _minute) {this._minute = _minute;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdTrendCountHistory{private Long clickedCountHistoryLong;public Long getClickedCountHistoryLong() {return clickedCountHistoryLong;}public void setClickedCountHistoryLong(Long clickedCountHistoryLong) {this.clickedCountHistoryLong = clickedCountHistoryLong;} } 本篇文章为转载内容。原文链接:https://blog.csdn.net/tom_8899_li/article/details/71194434。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-02-14 19:16:35
297
转载
Java
...Button , 在Java Swing库中,JRadioButton是用于创建图形用户界面(GUI)中的单选按钮的类。它允许用户从一组预定义选项中选择一项,同一组内的单选按钮互斥,一次只能选中一个。例如,在文章中,通过实例化三个JRadioButton对象并添加到ButtonGroup中,可以创建一个包含三个选项的单选框组。 ButtonGroup , 在Java Swing GUI编程中,ButtonGroup是一个容器类,主要用于管理一组JRadioButton组件。当多个单选按钮添加到同一个ButtonGroup时,系统会自动确保任何时候只有一个单选按钮处于选中状态,从而实现“单选”功能。在文章中,buttonGroup.add(radioButton1); 这样的语句就是将单选框添加至ButtonGroup进行分组管理。 JCheckBox , JCheckBox是Java Swing库提供的另一个重要组件,用于创建复选框。与JRadioButton不同,JCheckBox允许多选,用户可以选择任意数量的复选框,每个复选框的状态独立于其他复选框。在实际应用中,开发者可能需要根据业务需求创建多个JCheckBox对象来收集用户的多项选择信息。 (补充) GUI(图形用户界面) , GUI是一种用户与计算机程序交互的方式,它通过图像和图形元素(如按钮、文本框、单选框、复选框等)代替或辅助命令行界面的文字输入。在Java编程中,Swing和JavaFX是构建GUI的主要工具包,提供了丰富的API供开发者设计和实现各种图形界面组件。本文所讨论的单选框和复选框便是GUI中的两种常用控件,用于实现用户的选择交互功能。
2023-04-24 23:41:54
385
码农
Struts2
.... 引言 当我们谈论Java Web开发框架时,Struts2无疑是一个无法忽视的重要角色。它以其强大的MVC模式和丰富的标签库深受开发者喜爱。今天,咱们就来好好唠一唠,在JSP页面上如何灵活运用Struts2给咱提供的标签这个小玩意儿,让它帮咱们把藏在集合深处的数据统统挖出来,展示得明明白白的。这个过程就像一个寻宝游戏,让我们一起挖掘那些深藏在集合里的“宝藏”。 2. 标签概述 s:iterator标签是Struts2提供的一种用于迭代(遍历)集合或数组的强大工具。这个小家伙绝对是个实力派,它能轻轻松松地把后端送过来的一堆数据挨个儿展示在前端页面上,这可真是让我们的开发工作变得轻松多了,简直就像搭积木一样简单有趣! 3. 集合数据的准备与传递 首先,我们需要在Action类中准备一个集合,并将其作为属性值传递到视图层(JSP页面)。假设我们有一个包含多个用户信息的List: java public class UserAction extends ActionSupport { private List userList; // 假设User是一个实体类 public String execute() { // 初始化或者从数据库获取userList // ... return SUCCESS; } // getter and setter 方法 public List getUserList() { return userList; } public void setUserList(List userList) { this.userList = userList; } } 4. 在JSP中使用标签遍历集合 接下来,在JSP页面中,我们可以利用标签遍历上述的userList集合: jsp <%@ taglib prefix="s" uri="/struts-tags"%> ... ID Name Email 上述代码段中,value="userList"指定了要遍历的集合对象,而status="rowstatus"则定义了一个名为rowstatus的迭代状态变量,可以用来获取当前迭代的索引、是否为奇数行/偶数行等信息。 5. 迭代状态变量的应用 在实际应用中,迭代状态变量非常有用,例如,我们可以根据行号决定表格行的颜色: jsp oddRowevenRow"> 在这个示例中,我们通过rowstatus.odd检查当前行是否为奇数行,然后动态设置CSS样式。 6. 结语标签在处理集合数据时的灵活性和便捷性可见一斑。它不仅能让我们超级高效地跑遍所有数据,还能加上迭代状态变量这个小玩意儿,让前端展示效果噌噌噌地往上蹿,变得更带劲儿。在实际做项目开发这事儿的时候,要是能把这个特性玩得贼溜,还能灵活运用,那简直就像给咱们编写Web页面插上了一对翅膀,让代码读起来更明白易懂,维护起来也更加轻松省力。这就是编程最让人着迷的地方啦——就像一场永不停歇的探险,你得不断尝试、动手实践,让每一个细微的技术环节都化身为打造完美产品的强大力量。
2023-01-03 18:14:02
44
追梦人
Java
Java中的全角空格与半角空格 1. 引言 大家好!今天我要和大家聊聊Java编程中一个看似简单却容易被忽视的问题——全角空格与半角空格。这个小细节虽然不起眼,但在处理字符串时经常给我们惹出不少麻烦,真是让人头疼。作为一个喜欢编程的程序员,我经常碰到这种难题,每次搞定后都特有那种“终于拨开云雾见青天”的爽快感。今天,我就来分享一下我在这方面的经验和见解。 2. 全角空格与半角空格的概念 2.1 什么是全角空格? 全角空格,也叫中文空格,是一种宽字符,通常出现在中文文本中。它在Unicode编码中的位置是U+3000。你看,在屏幕上全角空格就像个大胖子,占的地方比半角空格多出不少。所以在排版的时候,用全角空格会让整个布局看起来更赏心悦目。 2.2 什么是半角空格? 半角空格,也叫英文空格,是一种窄字符,通常出现在英文文本中。它在Unicode编码中的位置是U+0020。在视觉上,半角空格占用的空间较小,适合在英文文本中使用。 3. 全角空格与半角空格在Java中的处理 3.1 如何区分全角空格与半角空格? 在Java中,我们可以利用Character类提供的方法来判断一个字符是否为全角空格或半角空格。例如: java public static boolean isFullWidthSpace(char c) { return c == '\u3000'; // 全角空格 } public static boolean isHalfWidthSpace(char c) { return c == ' '; // 半角空格 } 这里我们定义了两个方法isFullWidthSpace和isHalfWidthSpace,分别用于判断一个字符是否为全角空格或半角空格。这个方法虽然简单,但在实际应用中非常实用。 3.2 如何替换全角空格与半角空格? 有时候我们需要将文本中的全角空格替换为半角空格,或者反之。这时我们可以使用String类的replace或replaceAll方法。下面是一个具体的例子: java public class ReplaceSpaces { public static void main(String[] args) { String text = "这是一段包含全角空格的文字\u3000"; // 替换全角空格为半角空格 String result = text.replace('\u3000', ' '); System.out.println("替换后的结果:" + result); // 反之,替换半角空格为全角空格 String originalText = "This is a sentence with half-width spaces."; String fullWidthResult = originalText.replace(' ', '\u3000'); System.out.println("全角空格替换结果:" + fullWidthResult); } } 在这个例子中,我们首先将一段包含全角空格的文本中的全角空格替换为半角空格,然后反向操作,将一段英文文本中的半角空格替换为全角空格。用这种方法,我们就能够随心所欲地调整文本里的空格了,想怎么玩就怎么玩。 4. 实际应用案例 在实际开发中,我们经常会遇到需要处理各种复杂文本的情况。比如说,有时候用户会不小心输入全角空格,这玩意儿能直接让我们的程序翻车。这时候,我们就得对输入做一些处理,把那些全角空格换成半角空格,这样程序才能好好地工作。 假设我们正在开发一个文本编辑器,用户可以输入任意文本。为了确保文本不出错,我们在保存前得把全角空格换成半角空格。下面是实现这一功能的代码示例: java public class TextEditor { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入一段文本:"); String input = scanner.nextLine(); // 将全角空格替换为半角空格 String correctedInput = input.replace('\u3000', ' '); // 保存修正后的文本 saveText(correctedInput); System.out.println("文本已保存!"); } private static void saveText(String text) { // 这里可以添加保存文本的逻辑,例如保存到文件等 System.out.println("保存的内容:" + text); } } 在这个例子中,我们创建了一个简单的文本编辑器,用户可以输入一段文本。在保存文本之前,我们调用replace方法将其中的全角空格替换为半角空格,从而确保文本的正确性。这样一来,就算大伙儿一不小心打了个全角空格进来,我们的程序也能妥妥地应对,不会出岔子。 5. 总结 全角空格与半角空格在Java编程中是一个不容忽视的小细节。通过对它们的正确理解和处理,我们可以避免很多潜在的问题。希望大家在阅读本文后,能够掌握如何在Java中区分和处理这两种空格,从而在实际开发中更加得心应手。 最后,我想说的是,编程不仅是技术的较量,更是对细节的把握。每一个看似微不足道的小问题,都可能成为影响整个项目的关键。因此,我们要时刻保持警惕,不断学习和积累经验,才能成为一名优秀的程序员。希望我的分享能对你有所帮助,也欢迎你在评论区留言交流,让我们一起进步!
2024-12-22 15:53:15
89
风轻云淡
Apache Lucene
...处理大量数据并支持多用户访问的系统,权限控制是必不可少的一环。Apache Lucene,作为一款强大的全文搜索引擎,其核心功能在于高效地存储和检索文本数据。不过,当你看到好多用户一起挤在同一个索引上操作的时候,你会发现,确保数据安全,给不同权限的用户分配合适的“查看范围”,这可真是个大问题,而且是相当关键的一步!本文将深入探讨如何在多用户场景下集成Lucene,并实现基于角色的权限控制。 二、Lucene基础知识 首先,让我们回顾一下Lucene的基本工作原理。Lucene的核心组件包括IndexWriter用于创建和更新索引,IndexReader用于读取索引,以及QueryParser用于解析用户输入的查询语句。一个简单的索引创建示例: java import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.store.Directory; // 创建索引目录 Directory directory = FSDirectory.open(new File("indexdir")); // 分析器配置 Analyzer analyzer = new StandardAnalyzer(); // 索引配置 IndexWriterConfig config = new IndexWriterConfig(analyzer); config.setOpenMode(IndexWriterConfig.OpenMode.CREATE); // 创建索引写入器 IndexWriter indexWriter = new IndexWriter(directory, config); // 添加文档 Document doc = new Document(); doc.add(new TextField("content", "This is a test document.", Field.Store.YES)); indexWriter.addDocument(doc); // 关闭索引写入器 indexWriter.close(); 三、权限模型的构建 对于多用户场景,我们通常会采用基于角色的权限控制模型(Role-Based Access Control, RBAC)。例如,我们可以为管理员(Admin)、编辑(Editor)和普通用户(User)定义不同的索引访问权限。这可以通过在索引文档中添加元数据字段来实现: java Document doc = new Document(); doc.add(new StringField("content", "This is a protected document.", Field.Store.YES)); doc.add(new StringField("permissions", "Admin,Editor", Field.Store.YES)); // 添加用户权限字段 indexWriter.addDocument(doc); 四、权限验证与查询过滤 在处理查询时,我们需要检查用户的角色并根据其权限决定是否允许访问。以下是一个简单的查询处理方法: java public List search(String query, String userRole) { QueryParser parser = new QueryParser("content", analyzer); Query q = parser.parse(query); IndexSearcher searcher = new IndexSearcher(directory); Filter filter = null; if (userRole.equals("Admin")) { // 对所有用户开放 filter = Filter.ALL; } else if (userRole.equals("Editor")) { // 只允许Editor和Admin访问 filter = new TermFilter(new Term("permissions", "Editor,Admin")); } else if (userRole.equals("User")) { // 只允许User访问自己的文档 filter = new TermFilter(new Term("permissions", userRole)); } if (filter != null) { TopDocs results = searcher.search(q, Integer.MAX_VALUE, filter); return searcher.docIterator(results.scoreDocs).toList(); } else { return Collections.emptyList(); } } 五、权限控制的扩展与优化 随着用户量的增长,我们可能需要考虑更复杂的权限策略,如按时间段或特定资源的访问权限。这时,可以使用更高级的权限管理框架,如Spring Security与Lucene集成,来动态加载和管理角色和权限。 六、结论 在多用户场景下,Apache Lucene的强大检索能力与权限控制相结合,可以构建出高效且安全的数据管理系统。通过巧妙地设计索引布局,搭配上灵动的权限管理系统,再加上精准无比的查询筛选机制,我们能够保证每个用户都只能看到属于他们自己的“势力范围”内的数据,不会越雷池一步。这不仅提高了系统的安全性,也提升了用户体验。当然,实际应用中还需要根据具体需求不断调整和优化这些策略。 记住,Lucene就像一座宝库,它的潜力需要开发者们不断挖掘和适应,才能在各种复杂场景中发挥出最大的效能。
2024-03-24 10:57:10
436
落叶归根-t
Apache Solr
...松就把地理搜索功能给实现了。这样一来,开发者们就能随心所欲地定制出专属于自己的地理位置索引和检索服务,就像给自己家的地图装上了精准定位器一样方便。本篇文章将带你深入了解Solr如何在地理空间上施展它的魔力。 2. Apache Solr基础 Solr的核心在于它的强大查询解析能力,特别是利用Lucene的底层技术。它是一个基于Java的框架,允许我们扩展和优化搜索性能。首先,让我们看看如何在Solr中设置一个基本的地理搜索环境: java // 创建一个SolrServer实例 SolrServer server = new HttpSolrServer("http://localhost:8983/solr/mycore"); // 定义一个包含地理位置字段的Document对象 Document doc = new Document(); doc.addField("location", "40.7128,-74.0060"); // 纽约市坐标 3. 地理坐标编码 地理搜索的关键在于正确地编码和存储经纬度。Solr这家伙可灵活了,它能支持好几种地理编码格式,比如那个GeoJSON啦,还有WKT(别名Well-Known Text),这些它都玩得转。例如,我们可以使用Solr Spatial Component(SPT)来处理这些数据: java // 在schema.xml中添加地理位置字段 // 在添加文档时,使用GeoTools或类似库进行坐标编码 Coordinate coord = new Coordinate(40.7128, -74.0060); Point point = new Point(coord); String encodedLocation = SpatialUtil.encodePoint(point, "4326"); // WGS84坐标系 doc.addField("location", encodedLocation); 4. 地理范围查询(BoundingBox) Solr的Spatial Query模块允许我们执行基于地理位置的范围查询。例如,查找所有在纽约市方圆10公里内的文档: java // 构造一个查询参数 SolrQuery query = new SolrQuery(":"); query.setParam("fl", ",_geo_distance"); // 返回地理位置距离信息 query.setParam("q", "geodist(location,40.7128,-74.0060,10km)"); server.query(query); 5. 地理聚合(Geohash或Quadtree) Solr还支持地理空间聚合,如将文档分组到特定的地理区域(如GeoHash或Quadtree)。这有助于区域划分和统计分析: java // 使用Geohash进行区域划分 query.setParam("geohash", "radius(40.7128,-74.0060,10km)"); List geohashes = server.query(query).get("geohash"); 6. 神经网络搜索与地理距离排序 Solr 8.x及以上版本引入了神经网络搜索功能,允许使用深度学习模型优化地理位置相关查询。虽然具体实现依赖于Sease项目,但大致思路是将用户输入转换为潜在的地理坐标,然后进行精确匹配: java // 假设有一个预训练模型 NeuralSearchService neuralService = ...; double[] neuralCoordinates = neuralService.transform("New York City"); query.setParam("nn", "location:" + Arrays.toString(neuralCoordinates)); 7. 结论与展望 Apache Solr的地理搜索功能使得地理位置信息的索引和检索变得易如反掌。开发者们可以灵活运用各种Solr组件和拓展功能,像搭积木一样拼接出适应于五花八门场景的智能搜索引擎,让搜索变得更聪明、更给力。不过呢,随着科技的不断进步,Solr这个家伙肯定还会持续进化升级,没准儿哪天它就给我们带来更牛掰的功能,比如实时地理定位分析啊、预测功能啥的。这可绝对能让我们的搜索体验蹭蹭往上涨,变得越来越溜! 记住,Solr的强大之处在于它的可扩展性和社区支持,因此在实际应用中,持续学习和探索新特性是保持竞争力的关键。现在,你已经掌握了Solr地理搜索的基本原理,剩下的就是去实践中发现更多的可能性吧!
2024-03-06 11:31:08
405
红尘漫步-t
Tomcat
...,这可是个轻巧灵活的Java应用服务器小能手,它诞生于Apache Jakarta项目家族,内核构建基于Servlet规范和JSP规范这两块基石。这家伙最大的特点就是简单好上手、运行速度快稳如老狗,而且开源免费!深受广大中小型企业的喜爱,它们在进行Web开发和部署时,可没少请Tomcat出马帮忙。不过呢,虽然Tomcat这款应用服务器确实是顶呱呱的好用,但你要是不小心忽略了某些安全要点,它可就有可能被黑客小哥给盯上,成为他们眼中的“香饽饽”了。因此,我们需要了解一些防范措施,以保证我们的网站安全无虞。 接下来,我们来看看如何防止跨站脚本攻击(XSS)。XSS攻击,这可是网络安全界的一大“捣蛋鬼”。想象一下,坏人会在一些网站里偷偷塞进些恶意的小剧本。当咱们用户毫不知情地浏览这些网站时,那些小剧本就自动开演了,趁机把咱们的数据顺走,甚至可能连账号都给黑掉,引发各种让人头疼的安全问题。那么,我们应该如何防止这种攻击呢? 一种方法是使用HTTP-only cookie。当我们设置cookie时,我们可以指定是否允许JavaScript访问这个cookie。如果我们将此选项设为true,则JavaScript将不能读取这个cookie,从而避免了XSS攻击。例如: css Cookie = "name=value; HttpOnly" 另一种方法是在服务器端过滤所有的输入数据。这种方法可以确保用户输入的数据不会被恶意脚本篡改。比如,假如我们手头有个登录页面,那我们就能瞅瞅用户输入的用户名和密码对不对劲儿。要是发现不太对,咱就直接把这次请求给拒了,同时还得告诉他们哪里出了岔子,返回一个错误消息提醒一下。例如: php-template if (username != "admin" || password != "password") { return false; } 最后,我们还需要定期更新Tomcat和其他软件的安全补丁,以及使用最新的安全技术和工具,以提高我们的防御能力。另外,咱们还可以用上一些防火墙和入侵检测系统,就像给咱的网络装上电子眼和防护盾一样,实时留意着流量动态,一旦发现有啥不对劲的行为,就能立马出手拦截,确保安全无虞。 当然,除了上述方法外,还有很多其他的方法可以防止跨站脚本攻击(XSS),比如使用验证码、限制用户提交的内容类型等等。这些都是值得我们深入研究和实践的技术。 总的来说,防止访问网站时出现的安全性问题,如跨站脚本攻击(XSS)或SQL注入,是一项非常重要的任务。作为开发小哥/小姐姐,咱们得时刻瞪大眼睛,绷紧神经,不断提升咱的安全防护意识和技术能力。这样一来,才能保证我们的网站能够安安稳稳、健健康康地运行,不给任何安全隐患留空子钻。只有这样,我们才能赢得用户的信任和支持,实现我们的业务目标。"
2023-08-10 14:14:15
282
初心未变-t
SpringBoot
...变成了0。这不仅影响用户体验,也对代码调试提出了挑战。接下来,咱们一块儿踏上解谜之旅吧!从头开始,一点点弄懂这个神秘的“0”,就像拆开礼物上的层层包装,最终揭示它的奇妙真相。 二、场景再现 假设我们正在开发一个简单的用户注册系统,前端Vue.js负责收集用户信息,然后通过axios发送给SpringBoot后端进行验证和存储。你知道吗,有时候我们在Vue的那些小元件里边,填好账号名和密码,一激动点发送按钮,结果呢,后头的服务器接收的数据里,邮箱那一栏就莫名其妙地变成了0,就像被人动了手脚似的。 javascript // Vue.js 部分 - 送出数据的部分 methods: { registerUser() { const formData = { username: this.username, password: this.password, email: this.email, // 这里原本应该是用户的邮箱地址 }; axios.post('/api/register', formData) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); }); } } 三、问题分析 1. 类型转换 首先,检查一下是不是类型转换的问题。SpringBoot在接收数据时,如果类型不匹配,可能会尝试将其转换为可接受的数据类型。比如说,假如你邮箱地址栏不小心输入了个纯数字“0”,当你想把它当成字符串来处理的时候,这家伙可能会调皮地变成一个空荡荡的啥都没有。 java // SpringBoot 部分 - 接收数据的Controller @PostMapping("/register") public ResponseEntity registerUser(@RequestBody Map formData) { String email = formData.get("email").toString(); // 如果email是数字0,这里会变成"" // ... } 2. 默认值 另一个可能的原因是,前端在发送数据前没有正确处理可能的空值或默认值。你知道吗,有时候在发邮件前,email这哥们儿可能还没人填,这时它就暂且是JavaScript里的那个神秘存在“undefined”。一到要变成JSON格式,它就自动变身为“null”,然后后端大哥看见了,贴心地给它换个零蛋。 3. 数据验证 SpringBoot的@RequestBody注解默认会对JSON数据进行有效性校验,如果数据不符合约定的格式,它可能被视作无效,从而转化为默认值。检查Model层是否定义了默认值规则。 java // Model层 public class User { private String email; // ...其他字段 @NotBlank(message = "Email cannot be blank") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } 四、解决策略 1. 前端校验 确保在发送数据之前对前端数据进行清理和验证,避免空值或非预期值被发送。 2. 明确数据类型 在Vue.js中,可以使用v-model.number或者v-bind:value配合计算属性,确保数据在发送前已转换为正确的类型。 3. 后端配置 SpringBoot可以配置Jackson或Gson等JSON库,设置@JsonInclude(JsonInclude.Include.NON_NULL)来忽略所有空值。 4. 异常处理 添加适当的异常处理,捕获可能的转换异常并提供有用的错误消息。 五、结论 解决这个问题的关键在于理解数据流的每个环节,从前端到后端,每一个可能的类型转换和验证步骤都需要仔细审查。你知道吗,有时候生活就像个惊喜包,比如说JavaScript那些隐藏的小秘密,但别急,咱们一步步找,那问题的源头准能被咱们揪出来!希望这篇文章能帮助你在遇到类似困境时,更好地定位和解决“0”问题,提升开发效率和用户体验。 --- 当然,实际的代码示例可能需要根据你的项目结构和配置进行调整,以上只是一个通用的指导框架。记住,遇到问题时,耐心地查阅文档,结合调试工具,往往能更快地找到答案。祝你在前端与后端的交互之旅中一帆风顺!
2024-04-13 10:41:58
82
柳暗花明又一村_
Kotlin
...以其简洁、安全以及对Java兼容性的优势,赢得了众多开发者的心。哎呀,你知道吗?在Kotlin这个编程世界里,有个特别棒的功能叫做lateinit,它就像是给我们的代码加上了一个神奇的魔法。我们可以在类里先声明一个还没准备好值的属性,然后,就像变魔术一样,在后面的代码里再给它补上合适的值。这可是大大提高了代码的灵活性和可维护性!本文将深入探讨lateinit属性的使用方法、常见错误及其解决方案,帮助你更好地理解和利用这一特性。 1. 什么是Lateinit Property? lateinit是一个预定义的关键字,在Kotlin中用于声明一个属性,该属性可以在类外部被初始化,但必须在使用之前完成初始化。这意味着当你声明一个lateinit属性时,你承诺在代码执行过程中会调用其对应的初始化方法。哎呀,这个特性啊,它主要用在那些要到执行的时候才知道具体数值的玩意儿上头,或者在编程那会儿还不清楚确切数值咋整的情况。就像是你准备做饭,但到底加多少盐,得尝了味道再定,对吧?或者是你去超市买东西,但预算还没算好,得看商品价格了再做决定。这特性就跟那个差不多,灵活应变,随情况调整。 2. 示例代码 如何使用Lateinit Property? 首先,我们来看一个简单的例子,演示如何在类中声明并使用lateinit属性: kotlin class DataProcessor { lateinit var data: String fun loadData() { // 假设在这里从网络或其他源加载数据 data = "Processed Data" } } fun main() { val processor = DataProcessor() processor.loadData() println(processor.data) // 输出:Processed Data } 在这个例子中,data属性被声明为lateinit。这意味着在main函数中创建DataProcessor实例后,我们不能立即访问data属性,而是必须先调用loadData方法来初始化它。一旦初始化,就可以安全地访问和使用data属性了。 3. 使用Lateinit Property的注意事项 虽然lateinit属性提供了很大的灵活性,但在使用时也需要注意几个关键点: - 必须在使用前初始化:这是最基础的要求。如果你尝试在未初始化的状态下访问或使用lateinit属性,编译器会抛出IllegalStateException异常。 - 不可提前初始化:一旦lateinit属性被初始化,就不能再次修改其值。尝试这样做会导致运行时错误。 - 性能考量:虽然lateinit属性可以延迟初始化,但它可能会增加应用的启动时间和内存消耗,特别是在大量对象实例化时。 4. 遇到“Lateinit Property Not Initialized Before Use”错误怎么办? 当遇到这个错误时,通常意味着你试图访问或使用了一个未初始化的lateinit属性。解决这个问题的方法通常是: - 检查初始化逻辑:确保在使用属性之前,确实调用了对应的初始化方法或进行了必要的操作。 - 代码重构:如果可能,将属性的初始化逻辑移至更合适的位置,比如构造函数、特定方法或事件处理程序中。 - 避免不必要的延迟初始化:考虑是否真的需要延迟初始化,有时候提前初始化可能更为合理和高效。 5. 实践中的应用案例 在实际项目中,lateinit属性特别适用于依赖于用户输入、网络请求或文件读取等不确定因素的数据加载场景。例如,在构建一个基于用户选择的配置文件加载器时: kotlin class ConfigLoader { lateinit var config: Map fun loadConfig() { // 假设这里通过网络或文件系统加载配置 config = loadFromDisk() } } fun main() { val loader = ConfigLoader() loader.loadConfig() println(loader.config) // 此时config已初始化 } 在这个例子中,config属性的加载逻辑被封装在loadConfig方法中,确保在使用config之前,其已经被正确初始化。 结论 lateinit属性是Kotlin中一个强大而灵活的特性,它允许你推迟属性的初始化直到运行时。然而,正确使用这一特性需要谨慎考虑其潜在的性能影响和错误情况。通过理解其工作原理和最佳实践,你可以有效地利用lateinit属性来增强你的Kotlin代码,使其更加健壮和易于维护。
2024-08-23 15:40:12
94
幽谷听泉
转载文章
...21。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 1. JSP功能具体要求及命名 request对象的使用,模拟注册页面和功能; (1)第1个JSP页面,命名为login.jsp:该页面提供一个表单(标签、文本框、密码框、单选按钮、复选框、按钮、下拉列表框、列表框、多行文本框等模拟注册界面,可以参考给定的图片布局)。 ①在第1个页面,输入相应内容、选择相应内容、选择出生日期后,自动计算年龄并显示到对应文本框中。 ②用户可以输入或者选择相关内容,点击“注册”按钮将输入和选择的数据传递给第2个JSP页面result.jsp。 (2)第2个页面,命名为result.jsp:通过request对象获得注册页面的信息,然后在该页面以表格形式显示出来。如下图所示 (建议,可以将用户信息编写成一个实体类) 2.具体代码 (1)login.jsp <%@ page contentType="text/html; charset=GB2312"%><HTML><body><center><h2>模拟注册页面</h2></center><font size=3><h3><form action="case03ssy2result.jsp" method=post><br>用户名:<input type="text" size="16" minlength="6" maxlength="16" aligin="left" name="username">   <b><i>用户名由6~16个字符组成,包括汉字,数字,字母等</i></b></br><p>密 码: <input type="password" size="16" minlength="6" maxlength="16" aligin="left" name="pwd">   <b><i>密码由6~16个字符组成,包括数字,字母等</i></b></p><p>性 别: <input type="radio" value="男" name="sex"/>男 <input type="radio" value="女" name="sex"/>女   年龄:<input type="text" size="4" name="age" id="age" style="background-color:grey" readonly><p>出生日期:<select name="year" id="year" onblur="changeAge()"> <% for(int y=1990;y<=2010;y++){ %><option value="<%=y %>"><%=y %></option><%}%></select>年<select name="month"><% for(int m=1;m<=12;m++){ %><option value="<%=m%>"><%=m %></option><%} %></select>月<select name="day"> <% for(int d=1;d<=31;d++){ %><option value="<%=d %>"><%=d %></option><%} %></select>日</p><p>爱 好:<input type="checkbox" value="唱歌" name="hobbies" />唱歌<input type="checkbox" value="听歌" name="hobbies" />听歌<input type="checkbox" value="篮球" name="hobbies" />篮球<input type="checkbox" value="乒乓球" name="hobbies" />乒乓球<input type="checkbox" value="足球" name="hobbies" />足球<input type="checkbox" value="羽毛球" name="hobbies" />羽毛球</p><p>所学课程:<select name="course" multiple="multiple" size="10"><option value="计算机科学导论">计算机科学导论</option><option value="C程序设计基础">C程序设计基础</option><option value="数据结构">数据结构</option><option value="操作系统原理">操作系统原理</option><option value="软件工程概论">软件工程概论</option><option value="算法分析与设计">算法分析与设计</option><option value="Java编程基础">Java编程基础</option><option value="计算机网络">计算机网络</option><option value="数据库系统原理及应用">数据库系统原理及应用</option><option value="软件设计">软件设计</option><option value="软件测试">软件测试</option><option value="Java Web应用程序开发">Java Web应用程序开发</option><option value="组网工程">组网工程</option><option value="软件项目管理">软件项目管理</option><option value="云计算与大数据技术">云计算与大数据技术</option><option value="粮油信息处理及模式识别">粮油信息处理及模式识别</option><option value="软件开发案例分析">软件开发案例分析</option><option value="软件交互设计">软件交互设计</option></select>按住Ctrl按钮来选择多个项目</p><p>个人简历:<textArea name="cv" rows="3" cols="35" align="top" ></textArea></p><p><center><input type="submit" value="注册" name="submit"></center></p></form></h3></font><script type="text/javascript">function changeAge() {console.log("调用了函数");var nowData = new Date();console.log(nowData.getUTCFullYear());var nowYear = nowData.getUTCFullYear();console.log(document.getElementById("year").value)var year = document.getElementById("year").value;var age = nowYear - year;var e = document.getElementById("age");e.value = age;}</script></body></HTML> (2)result.jsp <%@ page contentType="text/html; charset=GB2312"%><%! public String handleStr(String s){try{ byte [] bb=s.getBytes("GB2312");s=new String(bb);}catch(Exception exp){}return s;}%><HTML><body bgcolor=yellow><font size=3><% request.setCharacterEncoding("GB2312");String username=request.getParameter("username");String pwd=request.getParameter("pwd");String sex=request.getParameter("sex");String year=request.getParameter("year");String month=request.getParameter("month");String day=request.getParameter("day");String age=request.getParameter("age");String hobbies[]=request.getParameterValues("hobbies");String course[]=request.getParameterValues("course");String cv=request.getParameter("cv");%>注册个人信息如下:<br><table border=2><tr><td><% out.print("用户名");%></td><td><% out.print("密码"); %></td><td><% out.print("性别"); %></td><td><% out.print("出生日期"); %></td><td><% out.print("年龄"); %></td><td><% out.print("爱好"); %></td><td><% out.print("所学课程"); %></td><td><% out.print("个人简历"); %></td></tr><tr><td><% out.print(username); %></td><td><% out.print(pwd); %></td><td><% out.print(sex); %></td><td><% out.print(year+"年"+month+"月"+day+"日"); %></td><td><% out.print(age); %></td><td><% if(hobbies==null){out.println("无");}else{ for(int m=0;m<hobbies.length;m++){out.print(handleStr(hobbies[m])+" ");} }%></td><td><% if(course==null){out.println("无");}else{ for(int n=0;n<course.length;n++){out.print(handleStr(course[n])+" ");} }%></td><td><% out.print(cv); %></td></tr></table></font></body></HTML> 3.运行结果 4.总结分析 在大体功能实现的基础上,虽然实现了用户信息登录与记录,但是此界面只能输入并记录一个用户 ,无法实现多用户,有待改正。另外,在登录界面年龄下拉列表没用考录闰年与平年的区别,把每个月份都设置为了31天。 求大佬改正。 本篇文章为转载内容。原文链接:https://blog.csdn.net/Pluto_ssy/article/details/121049221。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-08-15 09:02:21
113
转载
Apache Lucene
...的性能和灵活性成为了用户体验的关键因素之一。Apache Lucene,作为一款强大的全文搜索库,为我们提供了丰富的查询选项,其中之一就是FuzzyQuery,它允许我们在搜索时处理模糊匹配,即使用户输入的关键词可能不完全精确。今天,我们将深入剖析如何在实际项目中利用FuzzyQuery,让搜索体验更加人性化。 二、什么是FuzzyQuery 1. 概念解析 FuzzyQuery是Lucene中用于执行模糊搜索的核心工具,它通过计算查询词与索引中的单词之间的Levenshtein距离(也称编辑距离),找到那些相似度超过预设阈值的文档。你知道吗,编辑距离这玩意儿就像个搞笑的测谎游戏,它比量两个词串之间的亲密度,简单说就是,你要么得添字、减字或者动动手脚换个别字,最少几次才能让这两个词串变成亲兄弟一样挨着。 三、FuzzyQuery的使用示例 2. 编码实现 以下是一个简单的Java代码片段,展示了如何使用FuzzyQuery进行模糊搜索: java import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; public class FuzzySearchExample { public static void main(String[] args) throws Exception { Directory indexDir = new RAMDirectory(); // 创建内存索引 Analyzer analyzer = new StandardAnalyzer(); // 使用标准分析器 // 假设我们有一个文档集合,这里只创建一个简单的文档 Document doc = new Document(); doc.add(new TextField("content", "Lucene is awesome", Field.Store.YES)); IndexWriterConfig config = new IndexWriterConfig(analyzer); IndexWriter writer = new IndexWriter(indexDir, config); writer.addDocument(doc); writer.close(); String queryTerm = "Lucenes"; // 用户输入的模糊查询词 float fuzziness = 1f; // 设置模糊度,例如1代表允许一个字符的差异 QueryParser parser = new QueryParser("content", analyzer); FuzzyQuery fuzzyQuery = new FuzzyQuery(parser.parse(queryTerm), fuzziness); IndexReader reader = DirectoryReader.open(indexDir); TopDocs topDocs = searcher.search(fuzzyQuery, 10); // 返回最多10个匹配结果 for (ScoreDoc scoreDoc : topDocs.scoreDocs) { Document hitDoc = searcher.doc(scoreDoc.doc); System.out.println("Score: " + scoreDoc.score + ", Hit: " + hitDoc.get("content")); } reader.close(); } } 这段代码首先创建了一个简单的索引,然后构造了一个FuzzyQuery实例,指定要搜索的关键词和允许的最大编辑距离。搜索时,我们能看到即使用户输入的不是完全匹配的"Lucene",而是"Lucenes",FuzzyQuery也能返回相关的结果。 四、FuzzyQuery优化策略 3. 性能与优化 当处理大量数据时,FuzzyQuery可能会变得较慢,因为它的计算复杂度与搜索词的长度和索引的大小有关。为了提高效率,可以考虑以下策略: - 前缀匹配:使用PrefixQuery结合FuzzyQuery,仅搜索具有相同前缀的文档,这可以减少搜索范围。 - 阈值调整:根据应用需求调整模糊度阈值,更严格的阈值可以提高精确度,但搜索速度会下降。 - 分批处理:如果搜索结果过多,可以分批处理,先缩小范围,再逐步细化。 五、结论 4. 未来展望与总结 FuzzyQuery在提高搜索灵活性的同时,也对性能提出了挑战。要想在项目里游刃有余,得深入理解那些神奇的机制和巧妙的策略,这样才能精准又高效,就像个武林高手一样,既能一击即中,又能快如闪电。Lucene那强大的模糊搜索绝不仅仅是纠错能手,它还能在你打字时瞬间给出超贴心的拼写建议,让找东西变得超级简单,简直提升了搜寻乐趣好几倍!随着科技日新月异,Lucene这家伙也越变越聪明,咱们可真盼着瞧见那些超酷的新搜索招数,让找东西这事变得更聪明又快捷,就像点穴一样精准! 在构建现代应用程序时,了解并善用这些高级查询工具,无疑会让我们的搜索引擎更具竞争力。希望这个简单示例能帮助你开始在项目中运用FuzzyQuery,提升搜索的精准度和易用性。
2024-06-11 10:54:39
497
时光倒流
Kotlin
...,以其简洁的语法和对Java生态系统的兼容性,吸引了众多开发者。随着技术的不断进步,开发者们面临的挑战也日益多样化,其中之一便是如何在日益复杂的项目中有效地管理和处理参数错误。本文旨在探讨Kotlin在现代软件开发中的角色与挑战,特别是在面对非法参数异常时的应对策略和最佳实践。 Kotlin的角色与优势 Kotlin的出现,旨在解决Java语言的一些局限性,如静态类型检查、更清晰的语法、以及更好的控制流处理。在现代软件开发中,Kotlin不仅被用于构建原生Android应用,还在企业级应用、Web服务、后端开发等领域找到了自己的位置。它的类型安全性有助于减少运行时错误,使得开发过程更加高效和可靠。 面对非法参数的挑战 尽管Kotlin在设计上注重类型安全,但在实际开发中,非法参数异常仍然可能因各种原因发生,如用户输入错误、配置文件解析错误、或数据传输过程中的数据类型不匹配等。这些问题不仅影响用户体验,还可能导致应用崩溃或产生不可预测的行为。 应对策略与最佳实践 1. 输入验证:在接收外部输入时,实施严格的数据验证,确保所有参数符合预期的类型和格式。使用Kotlin的类型系统和模式匹配特性,可以实现简洁而强大的验证逻辑。 2. 类型转换与异常处理:合理利用Kotlin的类型转换和异常处理机制,如as?操作符和try-catch块,优雅地处理类型不匹配或转换失败的情况。 3. 依赖注入:采用依赖注入(DI)模式可以降低组件间的耦合度,使得在不同环境中复用代码更加容易,同时也便于进行测试和调试。 4. 单元测试与集成测试:通过编写针对不同场景的单元测试和集成测试,可以在开发早期发现并修复非法参数相关的错误,提高代码质量和稳定性。 5. 代码审查与持续集成:引入代码审查流程和自动化持续集成/持续部署(CI/CD)工具,可以帮助团队成员及时发现潜在的代码问题,包括非法参数异常的处理。 结论 在面对非法参数异常等挑战时,Kotlin提供了丰富的工具和机制,帮助开发者构建健壮、可维护的应用。通过采用上述策略和最佳实践,不仅可以有效减少错误的发生,还能提升代码的可读性和可维护性。随着Kotlin在更多领域的广泛应用,未来在处理类似问题时,开发者将能够更好地利用语言特性,实现更高的开发效率和产品质量。
2024-09-18 16:04:27
112
追梦人
ElasticSearch
...时候你可能会想到很多实现方法: 比如你的底层数据库用的是sql数据库(比如mysql):你可能会想到在对应字段上使用field1 like '%?%',?即用户输出的关键词 比如你的底层数据库用的是mongo:你可能会想到在对应字段上使用db.collection.find({ "field1": { $regex: /aaa/ } })做查询,aaa即用户输入的关键词 比如你的底层数据库用的是elasticsearch:那厉害了,专业全文搜索神奇,全文搜索或搜索相关的需求使用elasticsearch绝对是最合适的选择 比如你的底层数据库用的是hive、impala、clickhouse等大数据计算引擎:鸟枪换炮,其实用作全文索引和搜索的场景并不合适,你可能依旧会使用sql数据库那样用like做交互 2. 方案选择 调研之后,可能会发现对于数据量相对大一点的搜索场景,在当下流行的数据库或计算引擎中,elasticsearch是其中最合适的解决方案。 无论是sql的like、还是mongo的regex,在线上环境下,数据量较多的情况下,都不是很高效的查询,甚至有的公司的dba会禁止在线上使用类似的查询语法。 与elasticsearch是“亲戚”的,大家还常提到lucene、solr,但是无论从现在的发展趋势还是公司运维人才的储备(不得不说当下的运维人才中,对es熟悉的人才会更多一些),elasticsearch是相对较合适的选择。 一些大数据计算引擎,其实更多的适合OLAP场景。当然也完全可以使用,因为比如clickhouse、starrocks等的查询速度已经发展的非常快。但你会发现在中文分词搜索上,实现起来有一定困扰。 所以,如果你不差机器,首选方案还是elasticsearch。 3. elasticsearch的适用场景 3.1 经典的日志搜索场景 提到elasticsearch不得不提到它的几个好朋友: 一些公司里经常用elasticsearch来收集日志,然后用kibana来展示和分析。 展开来说,举个例子,你的app打印日志打印到了线上日志文件,当app出现故障你需要做定位筛查的时候,可能需要登录线上机器用grep命令各种查看。 但如果你不差机器资源,可以搭建上述架构,app的日志会被收集到elasticsearch中,最终你可以在kibana中查看日志,kibana里面可以很方面的做各种筛查操作。 这个流畅大概是这样的: 3.2 通用搜索场景 但是没有上图的beats、logstash、kibana,elasticsearch可以自己工作吗?完全可以的! elasticsearch也支持单机部署,数据规模不是很大的情况下,表现也是不错的。所以,你也不用担心因为自己机器资源不够而对elasticsearch望而却步。当然,单机部署的情况下,更多的适合自己玩,对于可靠性的要求就不能太苛刻了。 如果你在用宝塔,那你可以在宝塔面板,左侧“软件商店”中直接找到elasticsearch,并“没有痛苦”的安装。 本篇文章主要讨论选型,所以不涉及安装细节。 3.2.1 性能顾虑 上面提到了“表现”,其实性能只是elasticsearch的一个方面,主要你的机器资源足够(机器资源?对,包括你的机器个数,elasticsearch可以非常方便的横向扩展,以及单机的配置,cpu+内存,内存越高越好,elasticsearch比较吃内存!),它一定会给你很好的性能反应。试想,公司里的app打印线上日志的行数其实可比一般业务系统产生的订单数量要大很多很多,elasticsearch都可以常在日志的实时分析,所以如果你要做通用场景,而且机器资源不是问题,这是完全行得通的。 3.2.2 易用性和可玩性 此外,在使用elasticsearch的时候,会有很多的可玩性。这里不引经据典,呈现很多elasticsearch官方文章的列举优秀特性(当然,确实很优秀!)。 这里举几个例子: (1)中文分词:第一章提到的其它引擎几乎很难实现,elasticsearch对分词器的支持是原生的,因为elasticsearch天生就为全文索引而生,elasticsearch的汉语名字就是“弹性搜索”。这家伙可是专门搞搜索的! 有的朋友可能不了解分词器,比如你的一个字段里存储“今天我要吃冰激凌”,在分词器的加持下,es最终会存储为“今天|我|要|吃|冰激凌”,并且使用倒排索引的形式进行存储。当你搜索“冰激凌”的时候,可以很快的反馈回来。 关于elasticsearch的原理,这里不展开说明,分词器和倒排索引是elasticsearch的最基本的概念。如果有不了解的朋友,可以自行百度一下。而且这两个概念,与elasticsearch其实不挂钩,是搜索中的通用概念。 关于倒排索引,其核心表现如下图: 如果你要用mysql、mongo实现中文分词,这......其实挺麻烦的,可能在后面的版本支持中会实现的很好,但在当前的流行版本中,它们对中文分词是不够友好的。 mysql5.7之后支持外挂第三方分词器,支持中文分词。而在数据量较大的情况下,mysql的多机器部署几乎很难实现,elasticsearch可以很容易的水平扩展。 mongo支持西方语言的分词,但不支持中文、日语、汉语等东方语言,你需要在自己的逻辑代码中实现分词器。 ngram分词,你看看效果:依旧是“今天我要吃冰激凌”,ngram二元分词后即将得到结果“今天、天我、我要、要吃、吃冰、冰激、激凌”。这....,那你搜索冰激凌就搜不出来!咋办呢,当然可以使用三元分词。但是更好的解决方案还是中文分词器,但它们原生并不支持的。 (2)自定义排名场景:比如你的搜索“冰激凌”,结果中返回了有10条,这10条应该有你想对它指定的顺序。最简单的就是用默认的得分,但是如果你想人为干预这个得分怎么办? elasticsearch支持function_score功能(可以不用,这个是增强功能),es会在计算最终得分之前回调这个你指定的function_score回调函数,传入原始得分、行的原始数据,你可以在里面做计算,比如查询其它参考表、或查看是否是广告位,以得到新的score返回给用户。 function_scrore的功能不展开描述,是一个在自定义得分场景下十分有用又简单易用的功能!下面是一个使用示例,不仅如此,它是支持自定义函数的,自由度非常高。 (3)文本高亮:你用mysql或mongo也可以实现,比如用户搜索“冰激凌”,你只需要在逻辑代码中对“冰激凌”替换为“<span class='highlight-term'>冰激凌</span>”,然后前端做样式即可。但如果用户搜索了“好吃的冰激凌”咋办呢?还有就是英文大小写的场景,用户搜索"MAIN",那结果及时匹配到了“main”(小写的),这个单词是否应该高亮呢?也许这时候你会用业务代码实现toLowerCase下基于位置下标的匹配。 挺麻烦的吧,elasticsearch,自动可以返回高亮字段!并且可以自由指定高亮的html前后标签。 (4)实在太多了....这家伙天生为索引而生,而且版本还在不断地迭代。不差机器的话,用用吧! 4. 退而求其次 4.1 普通数据库 尽管elasticsearch在搜索场景下,是非常好用的利器!但是它比较消耗机器资源,如果你的数据规模并不大,而且想快速实现功能。你可以使用mysql或mongo来代替,完全没有问题。 技术是为了解决特定业务场景下的问题,结合当前手头的资源,适合自己的才是最好的。也许你搞了一个单机器的elasticsearch,单机器内存只有2G,它的表现并不会比mysql、mongo来的好。 当然,如果你为了使用上边提到的一些优秀的独有的特性,那elasticsearch一定还是最佳选择! 对于mysql(关系型数据库)和mongo(文档数据库)的区别这里不展开描述了,但对于搜索而言,两种都合适。有时候选型也不用很纠结,其实都是差不太多的东西,适合自己的、自己熟悉的、运维起来顺手的,就是最好的。 4.2 普通数据库实现中文分词搜索的原理 尽管mysql在5.7以后支持外挂第三方分词器,mongo在截止目前的版本中也不支持中文分词(你可能会看到一些文章中说可以指定language为chinese,但其实会报错的)。 其实当你选择普通数据库,你就不得不在逻辑代码中自己实现一套索引分词+搜索分词逻辑。 索引分词+搜索分词?为什么分开写,如果你有用过elasticsearch或solr,你会知道,在指定字段的时候,需要指定index分词器和search分词器。 下面以mongo为例做简要说明。 4.2.1 index分词器 意思是当数据“索引”截断如何分词。首先,这里必须要承认,数据之后存储了,才能被查询。在搜索中,这句话可以换成是“数据只有被索引了,才能被搜索”。 这时候请求打过来了,要索引一条数据,其中某字段是“今天我要吃冰激凌”,分词后得到“今天|我|要|吃|冰激凌”,这个就可以入库了。 如果你使用elasticsearch或solr,这个过程是自动的。如果你使用不支持外观分词器的常规数据库,这个过程你就要手动了,并把分词后的结果用空格分开(最好使用空格,因为西方语言的分词规则就是按空格拆分,以及逗号句号),存入数据库的一个待搜索的字段上。 效果如下图: 本站的其它博文中有介绍IKAnalyzer:https://www.52itw.com/java/6268.html 4.2.2 search分词器 当用户的查询请求打过来,用户输入了“好吃的冰激凌”,分词后得到“好吃|冰激凌”(“的”作为停用词stopwords,被自动忽略了,IKAnalyzer可以指定停用词表)。 于是这时候就回去上图的数据库表里面搜索“好吃 冰激凌”(与index分词器结果统一,还是用空格分隔)。 当然,对于mongo而言,你需要事先开启全文索引db.xxx.ensureIndex({content: "text"}),xxx是集合名,content是字段名,text是全文索引的标识。 mongo搜索的时候用这个语法:db.xxx.find( { $text: { $search: "好吃 冰激凌" } },{ score: { $meta: "textScore" } }).sort( { score: { $meta: "textScore" } } ) 4.2.3 索引库和存储库分开 为了减少单表的大小,为了让普通的列表查询、普通筛选可以跑的更快,你可以对原有的数据原封不动的做一张表。 然后对于搜索场景,再单独对需要被搜索的字段单独拎一张表出来! 然后二者之间做增量信号同步或定时差额同步,可能会有延迟,这个就看你能容忍多长时间(悄悄告诉你,elasticsearch也需要指定这个refresh时间,一般是1s到几秒、甚至分钟级。当然,二者的这个时间对饮的底层目的是不一样的)。 这样,搜索的时候先查询搜索库,拿到一个指针id的列表,然后拿到指针id的列表区存储里把数据一次性捞出来。当然,也是支持分页的,你查询搜索库其实也是普通的数据库查询嘛,支持分页参数的。 4.3 存储库和索引库的延伸阅读 很多有名的开源软件也是使用的存储库与索引库分离的技术方案,如apache atlas: apache atlas对于大数据领域的数据资产元数据管理、数据血缘上可谓是专家,也涉及资产搜索的特性,它的实现思路就是:从搜索库中做搜索、拿到key、再去存储库中做查询。 搜索库:上图右下角,可以看到使用的是elasticsearch、solr或lucene,多个选一个 存储库:上图左下角,可以看到使用的是Cassandra、HBase或BerkeleyDB,多个选一个 虽然apache atlas在只有搜索库或只有存储库的时候也可以很好的工作,但只针对于数据量并不大的场景。 搜索库,擅长搜索!存储库,擅长海量存储!搜索库多样化搜索,然后去存储库做点查。 当你的数据达到海量的时候,es+hbase也是一种很好的解决方案,不在这里展开说明了。
2024-01-27 17:49:04
537
admin-tim
SpringBoot
...个常见的需求,无论是用户上传图片、视频,还是后台上传配置文件,都需要高效且稳定的处理方式。哎呀,你知道Spring Boot这个Java Web框架吗?它可是个超级好用的小工具!为什么这么说呢?因为它超级简洁,上手快,部署起来也特别方便,所以很多搞程序的大佬们都特别喜欢用它来开发项目。就像是你去超市买菜,选了个特别省事儿的购物车,推起来既轻松又快捷,Spring Boot就是那个购物车,让你的编程之旅更顺畅,效率更高!本文将详细讲解如何使用Spring Boot进行文件上传,包括配置、编码示例以及一些最佳实践。 1. 配置文件上传 在开始之前,确保你的项目中包含了必要的依赖。通常,Spring Boot会自动配置文件上传功能,但为了明确和控制,我们可以通过application.properties或application.yml文件来设置文件上传的目录和大小限制。 properties application.properties spring.servlet.multipart.max-file-size=2MB spring.servlet.multipart.max-request-size=10MB upload.path=/path/to/upload/files 这里,我们设置了单个文件的最大大小为2MB,整个请求的最大大小为10MB,并指定了上传文件的保存路径。 2. 创建Controller处理文件上传 接下来,在你的Spring Boot项目中创建一个控制器(Controller)来处理文件上传请求。下面是一个简单的例子: java import org.springframework.core.io.InputStreamResource; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; @Controller public class FileUploadController { @PostMapping("/upload") public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) { try { // 检查文件是否存在 if (file.isEmpty()) { return ResponseEntity.badRequest().body("Failed to upload empty file."); } // 获取文件名和类型 String fileName = file.getOriginalFilename(); String contentType = file.getContentType(); // 保存文件到指定路径 File targetFile = new File(upload.path + fileName); Files.copy(file.getInputStream(), Paths.get(targetFile.getAbsolutePath())); return ResponseEntity.ok("File uploaded successfully: " + fileName); } catch (IOException e) { return ResponseEntity.internalServerError().body("Failed to upload file: " + e.getMessage()); } } } 3. 测试文件上传功能 在完成上述配置和编码后,你可以通过Postman或其他HTTP客户端向/upload端点发送一个包含文件的POST请求。确保在请求体中正确添加了文件参数,如: json { "file": "path/to/your/file" } 4. 处理异常与错误 在实际应用中,文件上传可能会遇到各种异常情况,如文件过大、文件类型不匹配、服务器存储空间不足等。在这次的案例里,我们已经用了一段 try-catch 的代码来应对一些常见的错误情况了。就像你在日常生活中遇到小问题时,会先尝试解决,如果解决不了,就会求助于他人或寻找其他方法一样。我们也是这样,先尝试执行一段代码,如果出现预料之外的问题,我们就用 catch 部分来处理这些意外状况,确保程序能继续运行下去,而不是直接崩溃。对于更复杂的场景,例如检查文件类型或大小限制,可以引入更精细的逻辑: java @PostMapping("/upload") public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) { if (!isValidFileType(file)) { return ResponseEntity.badRequest().body("Invalid file type."); } if (!isValidFileSize(file)) { return ResponseEntity.badRequest().body("File size exceeds limit."); } // ... } private boolean isValidFileType(MultipartFile file) { // Check file type logic here } private boolean isValidFileSize(MultipartFile file) { // Check file size logic here } 结语 通过以上步骤,你不仅能够实现在Spring Boot应用中进行文件上传的基本功能,还能根据具体需求进行扩展和优化。记住,良好的错误处理和用户反馈是提高用户体验的关键。希望这篇文章能帮助你更好地理解和运用Spring Boot进行文件上传操作。嘿,兄弟!你听过这样一句话吗?“实践出真知”,尤其是在咱们做项目的时候,更是得这么干!别管你是编程高手还是设计大师,多试错,多调整,才能找到最适合那个场景的那套方案。就像是做菜一样,不试试加点这个,少放点那个,怎么知道哪个味道最对路呢?所以啊,提升技能,咱们就得在实际操作中摸爬滚打,这样才能把技术玩儿到炉火纯青的地步!
2024-09-12 16:01:18
85
寂静森林
转载文章
...14。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 目录 效果 代码 SpringBoot Vue 效果 步骤 点击下载 在输入框输入下载的文件名称 点击暂停 再次点击开始 下载完成 代码 SpringBoot pom <!-- 做断点下载使用--><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.8.0</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency> controller package com.kang.controller;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.;import java.net.URLEncoder;import java.util.Optional;/ @Description 文件切片下载 @ClassName DownLoadController @Author 康世行 @Date 20:58 2023/2/22 @Version 1.0/@Controller@Slf4jpublic class DownLoadController {private final static String utf8 = "utf-8";@RequestMapping("/down")public void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {// 设置编码格式response.setCharacterEncoding(utf8);//获取文件路径String fileName=request.getParameter("fileName");String drive=request.getParameter("drive");//参数校验log.info(fileName,drive);//完整路径(路径拼接待优化-前端传输优化-后端从新格式化 )String pathAll=drive+":\\"+fileName;log.info("pathAll{}",pathAll);Optional<String> pathFlag = Optional.ofNullable(pathAll);File file=null;if (pathFlag.isPresent()){//根据文件名,读取file流file = new File(pathAll);log.info("文件路径是{}",pathAll);if (!file.exists()){log.warn("文件不存在");return;} }else {//请输入文件名log.warn("请输入文件名!");return;}InputStream is = null;OutputStream os = null;try {//分片下载long fSize = file.length();//获取长度response.setContentType("application/x-download");String file_Name = URLEncoder.encode(file.getName(),"UTF-8");response.addHeader("Content-Disposition","attachment;filename="+fileName);//根据前端传来的Range 判断支不支持分片下载response.setHeader("Accept-Range","bytes");//获取文件大小//response.setHeader("fSize",String.valueOf(fSize));response.setHeader("fName",file_Name);//定义断点long pos = 0,last = fSize-1,sum = 0;//判断前端需不需要分片下载if (null != request.getHeader("Range")){response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);String numRange = request.getHeader("Range").replaceAll("bytes=","");String[] strRange = numRange.split("-");if (strRange.length == 2){pos = Long.parseLong(strRange[0].trim());last = Long.parseLong(strRange[1].trim());//若结束字节超出文件大小 取文件大小if (last>fSize-1){last = fSize-1;} }else {//若只给一个长度 开始位置一直到结束pos = Long.parseLong(numRange.replaceAll("-","").trim());} }long rangeLenght = last-pos+1;String contentRange = new StringBuffer("bytes").append(pos).append("-").append(last).append("/").append(fSize).toString();response.setHeader("Content-Range",contentRange);// response.setHeader("Content-Lenght",String.valueOf(rangeLenght));os = new BufferedOutputStream(response.getOutputStream());is = new BufferedInputStream(new FileInputStream(file));is.skip(pos);//跳过已读的文件(重点,跳过之前已经读过的文件)byte[] buffer = new byte[1024];int lenght = 0;//相等证明读完while (sum < rangeLenght){lenght = is.read(buffer,0, (rangeLenght-sum)<=buffer.length? (int) (rangeLenght - sum) :buffer.length);sum = sum+lenght;os.write(buffer,0,lenght);}log.info("下载完成");}finally {if (is!= null){is.close();}if (os!=null){os.close();} }} } 启动成功 Vue <html xmlns:th="http://www.thymeleaf.org"><head><meta charset="utf-8"/><title>狂神说Java-ES仿京东实战</title><link rel="stylesheet" th:href="@{/css/style.css}"/></head><body class="pg"><div class="page" id="app"><div id="mallPage" class=" mallist tmall- page-not-market "><!-- 头部搜索 --><div id="header" class=" header-list-app"><div class="headerLayout"><div class="headerCon "><!-- Logo--><h1 id="mallLogo"><img th:src="@{/images/jdlogo.png}" alt=""></h1><div class="header-extra"><!--搜索--><div id="mallSearch" class="mall-search"><form name="searchTop" class="mallSearch-form clearfix"><fieldset><legend>天猫搜索</legend><div class="mallSearch-input clearfix"><div class="s-combobox" id="s-combobox-685"><div class="s-combobox-input-wrap"><input v-model="keyword" type="text" autocomplete="off" value="java" id="mq"class="s-combobox-input" aria-haspopup="true"></div></div><button type="submit" @click.prevent="searchKey" id="searchbtn">搜索</button></div></fieldset></form><ul class="relKeyTop"><li><a>狂神说Java</a></li><li><a>狂神说前端</a></li><li><a>狂神说Linux</a></li><li><a>狂神说大数据</a></li><li><a>狂神聊理财</a></li></ul></div></div></div></div></div><el-button @click="download" id="download">下载</el-button><!-- <el-button @click="concurrenceDownload" >并发下载测试</el-button>--><el-button @click="stop">停止</el-button><el-button @click="start">开始</el-button>{ {fileFinalOffset} }{ {contentList} }<el-progress type="circle" :percentage="percentage"></el-progress></div><!--前端使用Vue,实现前后端分离--><script th:src="@{/js/axios.min.js}"></script><script th:src="@{/js/vue.min.js}"></script><!-- 引入样式 --><link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"><!-- 引入组件库 --><script src="https://unpkg.com/element-ui/lib/index.js"></script><script>new Vue({ el: 'app',data: {keyword: '', //搜索关键字results: [] ,//搜索结果percentage: 0, // 下载进度filesCurrentPage:0,//文件开始偏移量fileFinalOffset:0, //文件最后偏移量stopRecursiveTags:true, //停止递归标签,默认是true 继续进行递归contentList: [], // 文件流数组breakpointResumeTags:false, //断点续传标签,默认是false 不进行断点续传temp:[],fileMap:new Map(),timer:null, //定时器名称},methods: {//根据关键字搜索商品信息searchKey(){var keyword=this.keyword;axios.get('/search/JD/search/'+keyword+"/1/10").then(res=>{this.results=res.data;//绑定数据console.log(this.results)console.table(this.results)})},//停止下载stop(){//改变递归标签为falsethis.stopRecursiveTags=false;},//开始下载start(){//重置递归标签为true 最后进行合并this.stopRecursiveTags=true;//重置断点续传标签this.breakpointResumeTags=true;//重新调用下载方法this.download();},// 分段下载需要后端配合download() {// 下载地址const url = "/down?fileName="+this.keyword.trim()+"&drive=E";console.log(url)const chunkSize = 1024 1024 50; // 单个分段大小,这里测试用100Mlet filesTotalSize = chunkSize; // 安装包总大小,默认100Mlet filesPages = 1; // 总共分几段下载//计算百分比之前先清空上次的if(this.percentage==100){this.percentage=0;}let sentAxios = (num) => {let rande = chunkSize;//判断是否开启了断点续传(断点续传没法并行-需要上次请求的结果作为参数)if (this.breakpointResumeTags){rande = ${Number(this.fileFinalOffset)+1}-${num chunkSize + 1};}else {if (num) {rande = ${(num - 1) chunkSize + 2}-${num chunkSize + 1};} else {// 第一次0-1方便获取总数,计算下载进度,每段下载字节范围区间rande = "0-1";} }let headers = {range: rande,};axios({method: "get",url: url.trim(),async: true,data: {},headers: headers,responseType: "blob"}).then((response) => {if (response.status == 200 || response.status == 206) {//检查了下才发现,后端对文件流做了一层封装,所以将content指向response.data即可const content = response.data;//截取文件总长度和最后偏移量let result= response.headers["content-range"].split("/");// 获取文件总大小,方便计算下载百分比filesTotalSize =result[1];//获取最后一片文件位置,用于断点续传this.fileFinalOffset=result[0].split("-")[1]// 计算总共页数,向上取整filesPages = Math.ceil(filesTotalSize / chunkSize);// 文件流数组this.contentList.push(content);// 递归获取文件数据(判断是否要继续递归)if (this.filesCurrentPage < filesPages&&this.stopRecursiveTags==true) {this.filesCurrentPage++;//计算下载百分比 当前下载的片数/总片数this.percentage=Number((this.contentList.length/filesPages)100).toFixed(2);sentAxios(this.filesCurrentPage);//结束递归return;}//递归标签为true 才进行下载if (this.stopRecursiveTags){// 文件名称const fileName =decodeURIComponent(response.headers["fname"]);//构造一个blob对象来处理数据const blob = new Blob(this.contentList);//对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性//IE10以上支持blob但是依然不支持downloadif ("download" in document.createElement("a")) {//支持a标签download的浏览器const link = document.createElement("a"); //创建a标签link.download = fileName; //a标签添加属性link.style.display = "none";link.href = URL.createObjectURL(blob);document.body.appendChild(link);link.click(); //执行下载URL.revokeObjectURL(link.href); //释放urldocument.body.removeChild(link); //释放标签} else {//其他浏览器navigator.msSaveBlob(blob, fileName);} }} else {//调用暂停方法,记录当前下载位置console.log("下载失败")} }).catch(function (error) {console.log(error);});};// 第一次获取数据方便获取总数sentAxios(this.filesCurrentPage);this.$message({message: '文件开始下载!',type: 'success'});} }})</script></body></html> 本篇文章为转载内容。原文链接:https://blog.csdn.net/kangshihang1998/article/details/129407214。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-19 08:12:45
546
转载
转载文章
...01。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 😎 知识点概览 为了方便后续回顾该项目时能够清晰的知道本章节讲了哪些内容,并且能够从该章节的笔记中得到一些帮助,所以在完成本章节的学习后在此对本章节所涉及到的知识点进行总结概述。 本章节为【学成在线】项目的 day15 的内容 根据 课程ID 搜索该课程已发布的课程信息,并返回该课程的所有课程计划信息。 将指定课程 发布时 所的课程计划的媒资信息保存到 teachplan_media_publish 表中, 根据 课程计划id 搜索该课程计划所对应的媒资信息,需要用到的是该课程计划对应的 m3u8 地址,用于在线播放视频,该接口在课程管理服务中开发,供学习服务进行远程调用。 在学习服务中远程调用 课程计划媒资信息查询接口,获取该课程计划的视频播放的 m3u8 url地址,并返回给前端,前端使用该 url 进行视频的在线播放。 在线学习完整的测试流程:媒资信息的上传、选择、发布到前端门户、搜索门户测试,在线学习的播放视频。 目录 内容会比较多,小伙伴门可以根据目录进行按需查阅。 文章目录 😎 知识点概览 目录 一、学习页面:查询课程计划 0x01 需求分析 0x02 Api接口 0x03 服务端开发 Controller Service 测试 0x04 前端开发 配置NGINX虚拟主机 前端 API 方法 前端 API 方法调用 测试 二、学习页面:获取视频播放地址 0x01 需求分析 0x02 课程发布:储存媒资信息 需求分析 数据模型 Dao Service 测试 0x03 Logstash:扫描课程计划媒资 创建索引 创建模板文件 配置 mysql.conf 启动 logstash.bat Logstash多实例运行 0x04 搜素服务:查询课程媒资接口 需求分析 Api接口定义 Service Controller 测试 三、在线学习:接口开发 0x01 需求分析 0x02 搭建开发环境 0x03 Api接口 0x04 服务端开发 需求分析 搜索服务注册Eureka 搜索服务客户端 自定义错误代码 Service Controller 测试 0x05 前端开发 需求分析 api方法 配置代理 视频播放页面 简单的测试 完整的测试 1、上传文件 一些问题 ~~方案1:删除本地分块文件重新尝试上传~~ 方案2:检查前端提交的MD5值是否正确 2、为课程计划选择媒资信息 3、前端门户测试 四、待完善的一些功能 😁 认识作者 一、学习页面:查询课程计划 0x01 需求分析 到目前为止,我们已可以编辑课程计划信息并上传课程视频,下一步我们要实现在线学习页面动态读取章节对应的视频并进行播放。在线学习页面所需要的信息有两类: 课程计划信息 课程学习信息(视频地址、学习进度等) 如下图: 在线学习集成媒资管理的需求如下: 1、在线学习页面显示课程计划 2、点击课程计划播放该课程计划对应的视频 本章节实现学习页面动态显示课程计划,进入不同课程的学习页面右侧动态显示当前课程的课程计划。 0x02 Api接口 课程计划信息从哪里获取? 在课程发布完成后会自动发布到一个 course_pub 的表中,logstash 会自动将课程发布后的信息自动采集到 ES 索引库中,这些信息也包含课程计划信息。 所以考虑性能要求,课程发布后对课程的查询统一从 ES 索引库中查询。 前端通过请求 搜索服务 获取课程信息,需要单独在 搜索服务 中定义课程信息查询接口。 本接口接收课程id,查询课程所有信息返回给前端。 我们在搜素服务 API 下添加以下方法 @ApiOperation("根据id搜索课程发布信息")public Map<String,CoursePub> getdetail(String id); 返回的课程信息为 json 结构:key 为课程id,value 为课程内容。 0x03 服务端开发 在搜索服务中开发查询课程信息接口。 Controller 在搜素服务下添加以下方法 / 根据id搜索课程发布信息 @param id 课程id @return JSON数据/@Override@GetMapping("/getdetail/{id}")public Map<String, CoursePub> getdetail(@PathVariable("id")String id) {return esCourseService.getdetail(id);} Service / 根据id搜索课程发布信息 @param id 课程id @return JSON数据/public Map<String, CoursePub> getdetail(String id) {//设置索引SearchRequest searchRequest = new SearchRequest(es_index);//设置类型searchRequest.types(es_type);//创建搜索源对象SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//设置查询条件,根据id进行查询searchSourceBuilder.query(QueryBuilders.termQuery("id",id));//这里不使用source的原字段过滤,查询所有字段// searchSourceBuilder.fetchSource(new String[]{"name", "grade", "charge","pic"}, newString[]{});//设置搜索源对象searchRequest.source(searchSourceBuilder);//执行搜索SearchResponse searchResponse = null;try {searchResponse = restHighLevelClient.search(searchRequest);} catch (IOException e) {e.printStackTrace();}//获取搜索结果SearchHits hits = searchResponse.getHits();SearchHit[] searchHits = hits.getHits(); //获取最优结果Map<String,CoursePub> map = new HashMap<>();for (SearchHit hit: searchHits) {//从搜索结果中取值并添加到coursePub对象Map<String, Object> sourceAsMap = hit.getSourceAsMap();String courseId = (String) sourceAsMap.get("id");String name = (String) sourceAsMap.get("name");String grade = (String) sourceAsMap.get("grade");String charge = (String) sourceAsMap.get("charge");String pic = (String) sourceAsMap.get("pic");String description = (String) sourceAsMap.get("description");String teachplan = (String) sourceAsMap.get("teachplan");CoursePub coursePub = new CoursePub();coursePub.setId(courseId);coursePub.setName(name);coursePub.setPic(pic);coursePub.setGrade(grade);coursePub.setTeachplan(teachplan);coursePub.setDescription(description);//设置map对象map.put(courseId,coursePub);}return map;} 测试 使用 swagger-ui 或 postman 测试查询课程信息接口。 0x04 前端开发 配置NGINX虚拟主机 学习中心的二级域名为 ucenter.xuecheng.com ,我们在 nginx 中配置 ucenter 虚拟主机。 学成网用户中心server {listen 80;server_name ucenter.xuecheng.com;个人中心location / {proxy_pass http://ucenter_server_pool;} } 前端ucenterupstream ucenter_server_pool{server 127.0.0.1:7081 weight=10;server 127.0.0.1:13000 weight=10;} 在学习中心要调用搜索的 API,使用 Nginx 解决代理,如下图: 在 ucenter 虚拟主机下配置搜索 Api 代理路径 后台搜索(公开api)upstream search_server_pool{server 127.0.0.1:40100 weight=10;} 学成网用户中心server {listen 80;server_name ucenter.xuecheng.com;个人中心location / {proxy_pass http://ucenter_server_pool;}后端搜索服务location /openapi/search/ {proxy_pass http://search_server_pool/search/;} } 前端 API 方法 在学习中心 xc-ui-pc-leanring 对课程信息的查询属于基础常用功能,所以我们将课程查询的 api 方法定义在base 模块下,如下图: 在system.js 中定义课程查询方法: import http from './public'export const course_view = id => {return http.requestGet('/openapi/search/course/getdetail/'+id);} 前端 API 方法调用 在 learning_video.vue 页面中调用课程信息查询接口得到课程计划,将课程计划json 串转成对象。 xc-ui-pc-leanring/src/module/course/page/learning_video.vue 1、定义视图 课程计划 <!--课程计划部分代码--><div class="navCont"><div class="course-weeklist"><div class="nav nav-stacked" v-for="(teachplan_first, index) in teachplanList"><div class="tit nav-justified text-center"><i class="pull-left glyphicon glyphicon-th-list"></i>{ {teachplan_first.pname} }<i class="pull-right"></i></div><li v-if="teachplan_first.children!=null" v-for="(teachplan_second, index) in teachplan_first.children"><i class="glyphicon glyphicon-check"></i><a :href="url" @click="study(teachplan_second.id)">{ {teachplan_second.pname} }</a></li><!-- <div class="tit nav-justified text-center"><i class="pull-left glyphicon glyphicon-th-list"></i>第一章<i class="pull-right"></i></div><li ><i class="glyphicon glyphicon-check"></i><a :href="url" >第一节</a></li>--><!--<li><i class="glyphicon glyphicon-unchecked"></i>为什么分为A、B、C部分</li>--></div></div></div> 课程名称 <div class="top text-center">{ {coursename} }</div> 定义数据对象 data() {return {url:'',//当前urlcourseId:'',//课程idchapter:'',//章节Idcoursename:'',//课程名称coursepic:'',//课程图片teachplanList:[],//课程计划playerOptions: {//播放参数autoplay: false,controls: true,sources: [{type: "application/x-mpegURL",src: ''}]},} } 在 created 钩子方法中获取课程信息 created(){//当前请求的urlthis.url = window.location//课程idthis.courseId = this.$route.params.courseId//章节idthis.chapter = this.$route.params.chapter//查询课程信息systemApi.course_view(this.courseId).then((view_course)=>{if(!view_course || !view_course[this.courseId]){this.$message.error("获取课程信息失败,请重新进入此页面!")return ;} let courseInfo = view_course[this.courseId]console.log(courseInfo)this.coursename = courseInfo.nameif(courseInfo.teachplan){let teachplan = JSON.parse(courseInfo.teachplan);this.teachplanList = teachplan.children;} })}, 测试 在浏览器请求:http://ucenter.xuecheng.com//learning/4028e581617f945f01617f9dabc40000/0 4028e581617f945f01617f9dabc40000:第一个参数为课程 id,测试时从 ES索引库找一个课程 id 0:第二个参数为课程计划 id,此参数用于点击课程计划播放视频。 如果出现跨域问题,但是确定已经配置了跨域,请尝试结束所以 nginx.exe 的进程 和 清空浏览器缓存。 如果还没有解决?重启电脑试试。 二、学习页面:获取视频播放地址 0x01 需求分析 用户进入在线学习页面,点击课程计划将播放该课程计划对应的教学视频。 业务流程如下: 业务流程说明: 1、用户进入在线学习页面,页面请求搜索服务获取课程信息(包括课程计划信息)并且在页面展示。 2、在线学习请求学习服务获取视频播放地址。 3、学习服务校验当前用户是否有权限学习,如果没有权限学习则提示用户。 4、学习服务校验通过,请求搜索服务获取课程媒资信息。 5、搜索服务请求ElasticSearch获取课程媒资信息。 为什么要请求 ElasticSearch 查询课程媒资信息? 出于性能的考虑,公开查询课程信息从搜索服务查询,分摊 mysql 数据库的访问压力。 什么时候将课程媒资信息存储到 ElasticSearch 中? 课程媒资信息是在课程发布的时候存入 ElasticSearch,因为课程发布后课程信息将基本不再修改。 0x02 课程发布:储存媒资信息 需求分析 课程媒资信息是在课程发布的时候存入 ElasticSearch 索引库,因为课程发布后课程信息将基本不再修改,具体的业务流程如下。 1、课程发布,向课程媒资信息表写入数据。 1)根据课程 id 删除 teachplanMediaPub 中的数据 2)根据课程 id 查询 teachplanMedia 数据 3)将查询到的 teachplanMedia 数据插入到 teachplanMediaPub 中 2、Logstash 定时扫描课程媒资信息表,并将课程媒资信息写入索引库。 数据模型 在 xc_course 数据库创建课程计划媒资发布表: CREATE TABLE teachplan_media_pub (teachplan_id varchar(32) NOT NULL COMMENT '课程计划id',media_id varchar(32) NOT NULL COMMENT '媒资文件id',media_fileoriginalname varchar(128) NOT NULL COMMENT '媒资文件的原始名称',media_url varchar(256) NOT NULL COMMENT '媒资文件访问地址',courseid varchar(32) NOT NULL COMMENT '课程Id',timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT'logstash使用',PRIMARY KEY (teachplan_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 数据模型类如下: package com.xuecheng.framework.domain.course;import lombok.Data;import lombok.ToString;import org.hibernate.annotations.GenericGenerator;import javax.persistence.;import java.io.Serializable;import java.util.Date;@Data@ToString@Entity@Table(name="teachplan_media_pub")@GenericGenerator(name = "jpa-assigned", strategy = "assigned")public class TeachplanMediaPub implements Serializable {private static final long serialVersionUID = -916357110051689485L;@Id@GeneratedValue(generator = "jpa-assigned")@Column(name="teachplan_id")private String teachplanId;@Column(name="media_id")private String mediaId;@Column(name="media_fileoriginalname")private String mediaFileOriginalName;@Column(name="media_url")private String mediaUrl;@Column(name="courseid")private String courseId;@Column(name="timestamp")private Date timestamp;//时间戳} Dao 创建 TeachplanMediaPub 表的 Dao,向 TeachplanMediaPub 存储信息采用先删除该课程的媒资信息,再添加该课程的媒资信息,所以这里定义根据课程 id 删除课程计划媒资方法: public interface TeachplanMediaPubRepository extends JpaRepository<TeachplanMediaPub, String> {//根据课程id删除课程计划媒资信息long deleteByCourseId(String courseId);} 从TeachplanMedia查询课程计划媒资信息 //从TeachplanMedia查询课程计划媒资信息public interface TeachplanMediaRepository extends JpaRepository<TeachplanMedia, String> {List<TeachplanMedia> findByCourseId(String courseId);} Service 编写保存课程计划媒资信息方法,并在课程发布时调用此方法。 1、保存课程计划媒资信息方法 本方法采用先删除该课程的媒资信息,再添加该课程的媒资信息,在 CourseService 下定义该方法 //保存课程计划媒资信息private void saveTeachplanMediaPub(String courseId){//查询课程媒资信息List<TeachplanMedia> byCourseId = teachplanMediaRepository.findByCourseId(courseId);if(byCourseId == null) return; //没有查询到媒资数据则直接结束该方法//将课程计划媒资信息储存到待索引表//删除原有的索引信息teachplanMediaPubRepository.deleteByCourseId(courseId);//一个课程可能会有多个媒资信息,遍历并使用list进行储存List<TeachplanMediaPub> teachplanMediaPubList = new ArrayList<>();for (TeachplanMedia teachplanMedia: byCourseId) {TeachplanMediaPub teachplanMediaPub = new TeachplanMediaPub();BeanUtils.copyProperties(teachplanMedia, teachplanMediaPub);teachplanMediaPubList.add(teachplanMediaPub);}//保存所有信息teachplanMediaPubRepository.saveAll(teachplanMediaPubList);} 2、课程发布时调用此方法 修改课程发布的 coursePublish 方法: ....//保存课程计划媒资信息到待索引表saveTeachplanMediaPub(courseId);//页面urlString pageUrl = cmsPostPageResult.getPageUrl();return new CoursePublishResult(CommonCode.SUCCESS,pageUrl);..... 测试 测试课程发布后是否成功将课程媒资信息存储到 teachplan_media_pub 中,测试流程如下: 1、指定一个课程 2、为课程计划添加课程媒资 3、执行课程发布 4、观察课程计划媒资信息是否存储至 teachplan_media_pub 中 注意:由于此测试仅用于测试发布课程计划媒资信息的功能,可暂时将 cms页面发布的功能暂时屏蔽,提高测试效率。 测试结果如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vrzs5589-1595567273126)(https://qnoss.codeyee.com/20200704_15/image7)] 0x03 Logstash:扫描课程计划媒资 Logstash 定时扫描课程媒资信息表,并将课程媒资信息写入索引库。 创建索引 1、创建 xc_course_media 索引 2、并向此索引创建如下映射 POST: http://localhost:9200/xc_course_media/doc/_mapping {"properties" : {"courseid" : {"type" : "keyword"},"teachplan_id" : {"type" : "keyword"},"media_id" : {"type" : "keyword"},"media_url" : {"index" : false,"type" : "text"},"media_fileoriginalname" : {"index" : false,"type" : "text"} }} 索引创建成功 创建模板文件 在 logstach 的 config 目录文件 xc_course_media_template.json 文件路径为 %ES_ROOT_DIR%/logstash6.8.8/config/xc_course_media_template.json %ES_ROOT_DIR% 为 ElasticSearch 和 logstash 的安装目录 内容如下: {"mappings" : {"doc" : {"properties" : {"courseid" : {"type" : "keyword"},"teachplan_id" : {"type" : "keyword"},"media_id" : {"type" : "keyword"},"media_url" : {"index" : false,"type" : "text"},"media_fileoriginalname" : {"index" : false,"type" : "text"} }},"template" : "xc_course_media"} } 配置 mysql.conf 在logstash的 config 目录下配置 mysql_course_media.conf 文件供 logstash 使用,logstash 会根据 mysql_course_media.conf 文件的配置的地址从 MySQL 中读取数据向 ES 中写入索引。 参考https://www.elastic.co/guide/en/logstash/current/plugins-inputs-jdbc.html 配置输入数据源和输出数据源。 input {stdin {} jdbc {jdbc_connection_string => "jdbc:mysql://localhost:3306/xc_course?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC" 数据库信息jdbc_user => "root"jdbc_password => "123123" MYSQL 驱动地址,修改为maven仓库对应的位置jdbc_driver_library => "D:/soft/apache-maven-3.5.4/repository/mysql/mysql-connector-java/5.1.40/mysql-connector-java-5.1.40.jar" the name of the driver class for mysqljdbc_driver_class => "com.mysql.jdbc.Driver"jdbc_paging_enabled => "true"jdbc_page_size => "50000"要执行的sql文件statement_filepath => "/conf/course.sql"statement => "select from teachplan_media_pub where timestamp > date_add(:sql_last_value,INTERVAL 8 HOUR)"定时配置schedule => " "record_last_run => truelast_run_metadata_path => "D:/soft/elasticsearch/logstash-6.8.8/config/xc_course_media_metadata"} } output {elasticsearch {ES的ip地址和端口hosts => "localhost:9200"hosts => ["localhost:9200","localhost:9202","localhost:9203"]ES索引库名称index => "xc_course_media"document_id => "%{teachplan_id}"document_type => "doc"template => "D:/soft/elasticsearch/logstash-6.8.8/config/xc_course_media_template.json"template_name =>"xc_course_media"template_overwrite =>"true"} stdout {日志输出codec => json_lines} } 启动 logstash.bat 启动 logstash.bat 采集 teachplan_media_pub 中的数据,向 ES 写入索引。 logstash.bat -f ../config/mysql_course_media.conf 课程发布成功后,Logstash 会自动参加 teachplan_media_pub 表中新增的数据,效果如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ILPBxfXi-1595567273134)(https://qnoss.codeyee.com/20200704_15/image10)] Logstash多实例运行 由于之前我们还启动了一个 Logstash 对课程的发布信息进行采集,所以如果想两个 logstash 实例同时运行,因为每个实例都有一个.lock文件,所以不能使用同一个目录来存放数据,所以我们需要使用 --path.data= 为每个实例指定单独的数据目录,具体的代码如下: 该配置是在windows下进行的 课程发布实例 logstash_start_course_pub.bat @title logstash in course_publogstash.bat -f ..\config\mysql.conf --path.data=../data/course_pub 课程计划媒体发布实例 logstash_start_teachplan_media.bat @title logstash i n teachplan_media_publogstash.bat -f ../config/mysql_course_media.conf --path.data=../data/teachplan_media/ 同时运行效果如下 0x04 搜素服务:查询课程媒资接口 需求分析 搜索服务 提供查询课程媒资接口,此接口供学习服务调用。 Api接口定义 @ApiOperation("根据课程计划查询媒资信息")public TeachplanMediaPub getmedia(String teachplanId); Service 1、配置课程计划媒资索引库等信息 在 application.yml 中配置 xuecheng:elasticsearch:hostlist: ${eshostlist:127.0.0.1:9200} 多个结点中间用逗号分隔course:index: xc_coursetype: docsource_field: id,name,grade,mt,st,charge,valid,pic,qq,price,price_old,status,studymodel,teachmode,expires,pub_time,start_time,end_timemedia:index: xc_course_mediatype: docsource_field: courseid,media_id,media_url,teachplan_id,media_fileoriginalname 2、service 方法开发 在 课程搜索服务 中定义课程媒资查询接口,为了适应后续需求,service 参数定义为数组,可一次查询多个课程计划的媒资信息。 / 根据一个或者多个课程计划id查询媒资信息 @param teachplanIds 课程id @return QueryResponseResult/public QueryResponseResult<TeachplanMediaPub> getmedia(String [] teachplanIds){//设置索引SearchRequest searchRequest = new SearchRequest(media_index);//设置类型searchRequest.types(media_type);//创建搜索源对象SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//源字段过滤String[] media_index_arr = media_field.split(",");searchSourceBuilder.fetchSource(media_index_arr, new String[]{});//查询条件,根据课程计划id查询(可以传入多个课程计划id)searchSourceBuilder.query(QueryBuilders.termsQuery("teachplan_id", teachplanIds));searchRequest.source(searchSourceBuilder);SearchResponse searchResponse = null;try {searchResponse = restHighLevelClient.search(searchRequest);} catch (IOException e) {e.printStackTrace();}//获取结果SearchHits hits = searchResponse.getHits();long totalHits = hits.getTotalHits();SearchHit[] searchHits = hits.getHits();//数据列表List<TeachplanMediaPub> teachplanMediaPubList = new ArrayList<>();for(SearchHit hit:searchHits){TeachplanMediaPub teachplanMediaPub =new TeachplanMediaPub();Map<String, Object> sourceAsMap = hit.getSourceAsMap();//取出课程计划媒资信息String courseid = (String) sourceAsMap.get("courseid");String media_id = (String) sourceAsMap.get("media_id");String media_url = (String) sourceAsMap.get("media_url");String teachplan_id = (String) sourceAsMap.get("teachplan_id");String media_fileoriginalname = (String) sourceAsMap.get("media_fileoriginalname");teachplanMediaPub.setCourseId(courseid);teachplanMediaPub.setMediaUrl(media_url);teachplanMediaPub.setMediaFileOriginalName(media_fileoriginalname);teachplanMediaPub.setMediaId(media_id);teachplanMediaPub.setTeachplanId(teachplan_id);//将对象加入到列表中teachplanMediaPubList.add(teachplanMediaPub);}//构建返回课程媒资信息对象QueryResult<TeachplanMediaPub> queryResult = new QueryResult<>();queryResult.setList(teachplanMediaPubList);queryResult.setTotal(totalHits);return new QueryResponseResult<TeachplanMediaPub>(CommonCode.SUCCESS,queryResult);} Controller / 根据课程计划id搜索发布后的媒资信息 @param teachplanId @return/@GetMapping(value="/getmedia/{teachplanId}")@Overridepublic TeachplanMediaPub getmedia(@PathVariable("teachplanId") String teachplanId) {//为了service的拓展性,所以我们service接收的是数组作为参数,以便后续开发查询多个ID的接口String[] teachplanIds = new String[]{teachplanId};//通过service查询ES获取课程媒资信息QueryResponseResult<TeachplanMediaPub> mediaPubQueryResponseResult = esCourseService.getmedia(teachplanIds);QueryResult<TeachplanMediaPub> queryResult = mediaPubQueryResponseResult.getQueryResult();if(queryResult!=null&& queryResult.getList()!=null&& queryResult.getList().size()>0){//返回课程计划对应课程媒资return queryResult.getList().get(0);} return new TeachplanMediaPub();} 测试 使用 swagger-ui 和 postman 测试课程媒资查询接口。 三、在线学习:接口开发 0x01 需求分析 根据下边的业务流程,本章节完成前端学习页面请求学习服务获取课程视频地址,并自动播放视频。 0x02 搭建开发环境 1、创建数据库 创建 xc_learning 数据库,学习数据库将记录学生的选课信息、学习信息。 导入:资料/xc_learning.sql 2、创建学习服务工程 参考课程管理服务工程结构,创建学习服务工程: 导入:资料/xc-service-learning.zip 项目工程结构如下 0x03 Api接口 此 api 接口是课程学习页面请求学习服务获取课程学习地址。 定义返回值类型: package com.xuecheng.framework.domain.learning.response;import com.xuecheng.framework.model.response.ResponseResult;import com.xuecheng.framework.model.response.ResultCode;import lombok.Data;import lombok.NoArgsConstructor;import lombok.ToString;@Data@ToString@NoArgsConstructorpublic class GetMediaResult extends ResponseResult {public GetMediaResult(ResultCode resultCode, String fileUrl) {super(resultCode);this.fileUrl = fileUrl;}//媒资文件播放地址private String fileUrl;} 定义接口,学习服务根据传入课程 ID、章节 Id(课程计划 ID)来取学习地址。 @Api(value = "录播课程学习管理",description = "录播课程学习管理")public interface CourseLearningControllerApi {@ApiOperation("获取课程学习地址")public GetMediaResult getMediaPlayUrl(String courseId,String teachplanId);} 0x04 服务端开发 需求分析 学习服务根据传入课程ID、章节Id(课程计划ID)请求搜索服务获取学习地址。 搜索服务注册Eureka 学习服务要调用搜索服务查询课程媒资信息,所以需要将搜索服务注册到 eureka 中。 1、查看服务名称是否为 xc-service-search 注意修改application.xml中的服务名称:spring:application:name: xc‐service‐search 2、配置搜索服务的配置文件 application.yml,加入 Eureka 配置 如下: eureka:client:registerWithEureka: true 服务注册开关fetchRegistry: true 服务发现开关serviceUrl: Eureka客户端与Eureka服务端进行交互的地址,多个中间用逗号分隔defaultZone: ${EUREKA_SERVER:http://localhost:50101/eureka/,http://localhost:50102/eureka/}instance:prefer-ip-address: true 将自己的ip地址注册到Eureka服务中ip-address: ${IP_ADDRESS:127.0.0.1}instance-id: ${spring.application.name}:${server.port} 指定实例idribbon:MaxAutoRetries: 2 最大重试次数,当Eureka中可以找到服务,但是服务连不上时将会重试,如果eureka中找不到服务则直接走断路器MaxAutoRetriesNextServer: 3 切换实例的重试次数OkToRetryOnAllOperations: false 对所有操作请求都进行重试,如果是get则可以,如果是post,put等操作没有实现幂等的情况下是很危险的,所以设置为falseConnectTimeout: 5000 请求连接的超时时间ReadTimeout: 6000 请求处理的超时时间 3、添加 eureka 依赖 <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring‐cloud‐starter‐netflix‐eureka‐client</artifactId></dependency> 4、修改启动类,在class上添加如下注解: @EnableDiscoveryClient 搜索服务客户端 在 学习服务 创建搜索服务的客户端接口,此接口会生成代理对象,调用搜索服务: package com.xuecheng.learning.client;import com.xuecheng.framework.domain.course.TeachplanMediaPub;import org.springframework.cloud.openfeign.FeignClient;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;@FeignClient(value = "xc‐service‐search")public interface CourseSearchClient {@GetMapping(value="/getmedia/{teachplanId}")public TeachplanMediaPub getmedia(@PathVariable("teachplanId") String teachplanId);} 自定义错误代码 我们在 com.xuecheng.framework.domain.learning.response 包下自定义一个错误消息模型 package com.xuecheng.framework.domain.learning.response;import com.xuecheng.framework.model.response.ResultCode;import lombok.ToString;@ToStringpublic enum LearningCode implements ResultCode {LEARNING_GET_MEDIA_ERROR(false,23001,"学习中心获取媒资信息错误!");//操作代码boolean success;//操作代码int code;//提示信息String message;private LearningCode(boolean success, int code, String message){this.success = success;this.code = code;this.message = message;}@Overridepublic boolean success() {return success;}@Overridepublic int code() {return code;}@Overridepublic String message() {return message;} } 该消息模型基于 ResultCode 来实现,代码如下 package com.xuecheng.framework.model.response;/ Created by mrt on 2018/3/5. 10000-- 通用错误代码 22000-- 媒资错误代码 23000-- 用户中心错误代码 24000-- cms错误代码 25000-- 文件系统/public interface ResultCode {//操作是否成功,true为成功,false操作失败boolean success();//操作代码int code();//提示信息String message(); 从 ResultCode 中我们可以看出,我们约定了用户中心的错误代码使用 23000,所以我们定义的一些错误信息的代码就从 23000 开始计数。 Service 在学习服务中定义 service 方法,此方法远程请求课程管理服务、媒资管理服务获取课程学习地址。 package com.xuecheng.learning.service.impl;import com.netflix.discovery.converters.Auto;import com.xuecheng.framework.domain.course.TeachplanMediaPub;import com.xuecheng.framework.domain.learning.response.GetMediaResult;import com.xuecheng.framework.exception.ExceptionCast;import com.xuecheng.framework.model.response.CommonCode;import com.xuecheng.learning.client.CourseSearchClient;import com.xuecheng.learning.service.LearningService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class LearningServiceImpl implements LearningService {@AutowiredCourseSearchClient courseSearchClient;/ 远程调用搜索服务获取已发布媒体信息中的url @param courseId 课程id @param teachplanId 媒体信息id @return/@Overridepublic GetMediaResult getMediaPlayUrl(String courseId, String teachplanId) {//校验学生权限,是否已付费等//远程调用搜索服务进行查询媒体信息TeachplanMediaPub mediaPub = courseSearchClient.getmedia(teachplanId);if(mediaPub == null) ExceptionCast.cast(CommonCode.FAIL);return new GetMediaResult(CommonCode.SUCCESS, mediaPub.getMediaUrl());} } Controller 调用 service 根据课程计划 id 查询视频播放地址: @RestController@RequestMapping("/learning/course")public class CourseLearningController implements CourseLearningControllerApi {@AutowiredLearningService learningService;@Override@GetMapping("/getmedia/{courseId}/{teachplanId}")public GetMediaResult getMediaPlayUrl(@PathVariable String courseId, @PathVariable String teachplanId) {//获取课程学习地址return learningService.getMedia(courseId, teachplanId);} } 测试 使用 swagger-ui 或postman 测试学习服务查询课程视频地址接口。 0x05 前端开发 需求分析 需要在学习中心前端页面需要完成如下功能: 1、进入课程学习页面需要带上 课程 Id参数及课程计划Id的参数,其中 课程 Id 参数必带,课程计划 Id 可以为空。 2、进入页面根据 课程 Id 取出该课程的课程计划显示在右侧。 3、进入页面后判断如果请求参数中有课程计划 Id 则播放该章节的视频。 4、进入页面后判断如果 课程计划id 为0则需要取出本课程第一个 课程计划的Id,并播放第一个课程计划的视频。 进入到模块 xc-ui-pc-leanring/src/module/course api方法 let sysConfig = require('@/../config/sysConfig')let apiUrl = sysConfig.xcApiUrlPre;/获取播放地址/export const get_media = (courseId,chapter) => {return http.requestGet(apiUrl+'/api/learning/course/getmedia/'+courseId+'/'+chapter);} 配置代理 在 Nginx 中的 ucenter.xuecheng.com 虚拟主机中配置 /api/learning/ 的路径转发,此url 请转发到学习服务。 学习服务upstream learning_server_pool{server 127.0.0.1:40600 weight=10;}学成网用户中心server {listen 80;server_name ucenter.xuecheng.com;个人中心location / {proxy_pass http://ucenter_server_pool;}后端搜索服务location /openapi/search/ {proxy_pass http://search_server_pool/search/; }学习服务location ^~ /api/learning/ {proxy_pass http://learning_server_pool/learning/;} } 视频播放页面 1、如果传入的课程计划id为0则取出第一个课程计划id 在 created 钩子方法中完成 created(){//当前请求的urlthis.url = window.location//课程idthis.courseId = this.$route.params.courseId//章节idthis.chapter = this.$route.params.chapter//查询课程信息systemApi.course_view(this.courseId).then((view_course)=>{if(!view_course || !view_course[this.courseId]){this.$message.error("获取课程信息失败,请重新进入此页面!")return ;}let courseInfo = view_course[this.courseId]console.log(courseInfo)this.coursename = courseInfo.nameif(courseInfo.teachplan){console.log("准备开始播放视频")let teachplan = JSON.parse(courseInfo.teachplan);this.teachplanList = teachplan.children;//开始学习if(this.chapter == "0" || !this.chapter){//取出第一个教学计划this.chapter = this.getFirstTeachplan();console.log("第一个教学计划id为 ",this.chapter);this.study(this.chapter);}else{this.study(this.chapter);} }})}, 取出第一个章节 id,用户未输入课程计划 id 或者输入为 0 时,播放第一个。 //取出第一个章节getFirstTeachplan(){for(var i=0;i<this.teachplanList.length;i++){let firstTeachplan = this.teachplanList[i];//如果当前children存在,则取出第一个返回if(firstTeachplan.children && firstTeachplan.children.length>0){let secondTeachplan = firstTeachplan.children[0];return secondTeachplan.id;} }return ;}, 开始学习: //开始学习study(chapter){// 获取播放地址courseApi.get_media(this.courseId,chapter).then((res)=>{if(res.success){let fileUrl = sysConfig.videoUrl + res.fileUrl//播放视频this.playvideo(fileUrl)}else if(res.message){this.$message.error(res.message)}else{this.$message.error("播放视频失败,请刷新页面重试")} }).catch(res=>{this.$message.error("播放视频失败,请刷新页面重试")});}, 2、点击右侧课程章节切换播放 在原有代码基础上添加 click 事件,点击调用开始学习方法(study)。 <li v‐if="teachplan_first.children!=null" v‐for="(teachplan_second, index) inteachplan_first.children"><i class="glyphicon glyphicon‐check"></i><a :href="url" @click="study(teachplan_second.id)">{ {teachplan_second.pname} }</a></li> 3、地址栏路由url变更 这里需要注意一个问题,在用户点击课程章节切换播放时,地址栏的 url 也应该同步改变为当前所选择的课程计划 id 4、在线学习按钮 将 learnstatus 默认更改为 1,这样就能显示出马上学习的按钮,方便我们后续的集成测试。 文件路径为 xc-ui-pc-static-portal/include/course_detail_dynamic.html 部分代码块如下 <script>var body= new Vue({ //创建一个Vue的实例el: "body", //挂载点是id="app"的地方data: {editLoading: false,title:'测试',courseId:'',charge:'',//203001免费,203002收费learnstatus: 1 ,//课程状态,1:马上学习,2:立即报名、3:立即购买course:{},companyId:'template',company_stat:[],course_stat:{"s601001":"","s601002":"","s601003":""} }, 简单的测试 访问在线学习页面:http://ucenter.xuecheng.com//learning/课程id/课程计划id 通过 url 传入两个参数:课程id 和 课程计划id 如果没有课程计划则传入0 测试项目如下: 1、传入正确的课程id、课程计划id,自动播放本章节的视频 2、传入正确的课程id、课程计划id传入0,自动播放第一个视频 3、传入错误的课程id 或 课程计划id,提示错误信息。 4、通过右侧章节目录切换章节及播放视频。 访问: http://ucenter.xuecheng.com//learning/4028e58161bcf7f40161bcf8b77c0000/4028e58161bd18ea0161bd1f73190008 传入正确的课程id、课程计划id,自动播放本章节的视频 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ef0xxym7-1595567273153)(https://qnoss.codeyee.com/20200704_15/image17)] 传入正确的课程id、课程计划id传入0,自动播放第一个视频 访问 http://ucenter.xuecheng.com//learning/4028e58161bcf7f40161bcf8b77c0000/0 识别出第一个课程计划的 id 需要注意的是这里的 chapter 参数是我自己在 study 函数里加上去的,可以忽略。 传入错误的课程id或课程计划id,提示错误信息。 通过右侧章节目录切换章节及播放视频。 点击章节即可播放,但是点击制定章节后 url 没有发生改变,这个问题暂时还没有解决,关注笔记后面的内容。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TOGdxwb4-1595567273158)(https://qnoss.codeyee.com/20200704_15/image20)] 完整的测试 准备工作 启动 RabbitMQ,启动 Logstash、ElasticSearch 建议把所有后端服务都开起来 启动 前端静态门户、启动 nginx 、启动课程管理前端 我们整理一下测试的流程 上传两个媒资视频文件,用于测试 进入到课程管理,为课程计划选择媒资信息 发布课程,等待 logstash 将数据采集到 ElasticSearch 的索引库中 进入学成网主页,点击课程,进入到搜索门户页面 搜索课程,进入到课程详情页面 点击开始学习,进入到课程学习页面,选择课程计划中的一个章节进行学习。 1、上传文件 首先我们使用之前开发的媒资管理模块,上传两个视频文件用于测试。 第一个文件上传成功 一些问题 在上传第二个文件时,发生了错误,我们来检查一下问题出在了哪里 在媒体服务的控制台中可以看到,在 mergeChunks 方法在校验文件 md5 时候抛出了异常 我们在 MD5 校验这里打个断点,重新上传文件,分析一下问题所在。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OpEMZGI8-1595567273166)(https://qnoss.codeyee.com/20200704_15/image23)] 单步调试后发现,合并文件后的MD5值与用户上传的源文件值不相等 方案1:删除本地分块文件重新尝试上传 考虑到可能是在用户上传完 视频的分块文件时发生了一些问题,导致合并文件后与源文件的大小不等,导致MD5也不相同,这里我们把这个视频上传到本地的文件全部删除,在媒资上传页面重新上传文件。 对比所有分块文件的字节大小和本地源文件的大小,完全是相等的 删除所有文件后重新上传,md5值还是不等,考虑从调试一下文件合并的代码。 方案2:检查前端提交的MD5值是否正确 在查阅是否有其他的MD5值获取方案时,发现了一个使用 windows 本地命令获取文件MD5值的方法 certutil -hashfile .\19-在线学习接口-集成测试.avi md5 惊奇的发现,TM的原来是前端那边转换的MD5值不正确,后端这边是没有问题的。 从前面的图可以看出,本地和后端转换的都是以一个 f6f0 开头的MD5值 那么问题就出现在前端了,还需要花一些时间去分析一下,这里暂时就先告一段落,因为上传了几个文件测试中只有这一个文件出现了问题。 2、为课程计划选择媒资信息 进入到一个课程的管理页面 http://localhost:12000//course/manage/baseinfo/4028e58161bcf7f40161bcf8b77c0000 将刚才我们上传的媒资文件的信息和课程计划绑定 选择效果如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-epKaqzCD-1595567273178)(https://qnoss.codeyee.com/20200704_15/image29)] 2、发布课程,等待 logstash 从 course_pub 以及 teachplan_media_pub 表中采集数据到 ElasticSearch 当中 发布成功后,我们可以从 teachplan_media_pub 表中看到刚才我们发布的媒资信息 再观察 Logstash 的控制台,发现两个 Logstash 的实例都对更新的课程发布信息进行了采集 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hTUve2ik-1595567273183)(https://qnoss.codeyee.com/20200704_15/image32)] 3、前端门户测试 打开我们的门户主站 http://www.xuecheng.com/ [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4wZe9R84-1595567273185)(https://qnoss.codeyee.com/20200704_15/image33)] 点击导航栏的课程,进入到我们的搜索门户页面 如果无法进入到搜索门户,请检查你的 xc-ui-pc-portal 前端工程是否已经启动 进入到搜索门户后,可以看到一些初始化时搜索的课程数据,默认是搜索第一页的数据,每页2个课程。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BJ1AKoJb-1595567273187)(https://qnoss.codeyee.com/20200704_15/image34)] 我们可以测试搜索一下前面我们选择媒资信息时所用的课程 点击课程,进入到课程详情页面,然后再点击开始学习。 点击马上学习后,会进入到该课程的在线学习页面,默认自动播放我们第一个课程计划中的视频。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tcuLWnf2-1595567273193)(https://qnoss.codeyee.com/20200704_15/image37)] 我们可以在右侧的目录中选择第二个课程计划,会自动播放所选的课程计划所对应的媒资视频播放地址,该 播放地址正是我们刚才通过 Logstash 自动采集到 ElasticSearch 的索引信息,效果图如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Cvi9Dr0Y-1595567273195)(https://qnoss.codeyee.com/20200704_15/image38)] 四、待完善的一些功能 课程发布前,校验课程计划里面是否包含二级课程计划 课程发布前,校验课程计划信息里面是否全部包含媒资信息 删除媒资信息,并且同步删除ES中的索引 在获取该课程的播放地址时校验用户的合法、 在线学习页面,点击右侧目录中的课程计划同时改变url中的课程计划地址 视频文件 19-在线学习接口-集成测试.avi 前端上传时提交的MD5值不正确 😁 认识作者 作者:👦 LCyee ,全干型代码🐕 自建博客:https://www.codeyee.com 记录学习以及项目开发过程中的笔记与心得,记录认知迭代的过程,分享想法与观点。 CSDN 博客:https://blog.csdn.net/codeyee 记录和分享一些开发过程中遇到的问题以及解决的思路。 欢迎加入微服务练习生的队伍,一起交流项目学习过程中的一些问题、分享学习心得等,不定期组织一起刷题、刷项目,共同见证成长。 本篇文章为转载内容。原文链接:https://blog.csdn.net/codeyee/article/details/107558901。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-16 12:41:01
73
转载
转载文章
...样至关重要。 另外,Java 8及以上版本引入了全新的日期和时间API(java.time包),提供了更强大且灵活的方式来处理日期、时间和时区问题。LocalDateTime、Duration和Period等类可以高效准确地完成时间单位之间的转换,包括毫秒到小时、分钟、秒的转换,同时支持格式化输出。 不仅如此,对于大规模分布式系统,微服务架构下的各个组件间的时间同步也是基础能力之一,NTP(网络时间协议)等协议便承担着将UTC时间精确到毫秒级同步到全球各节点的任务。而在呈现给终端用户时,仍需经过类似上述"convertMillis"方法的处理,转化为人性化的“小时:分钟:秒”格式。 综上所述,无论是基础的编程实践还是高级的应用场景,将毫秒数转换为小时、分钟、秒不仅是一种基本技能,更是解决复杂时间管理问题的关键环节。与时俱进地掌握并运用相关技术和最佳实践,有助于提升系统的可靠性和用户体验。
2024-03-25 12:35:31
506
转载
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
tar --list -f archive.tar.gz
- 列出压缩包内的文件列表。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"