前端技术
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 Message Service...]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
HessianRPC
...和反序列化的游戏,让Java和其他各种编程语言能够无缝对接、高效沟通,就像一个随叫随到、传递消息的小信使一样。然而,在实际操作时,我们可能时不时会遇到个头疼的问题——“HessianURLException:在捣鼓或者构建URL时出了岔子。”嘿,老铁们,这次咱要聊的这个主题可有点意思了。这篇东西呢,就是专门针对这种“诡异现象”,打算手把手地带大家伙儿通过一些实实在在的代码实例,抽丝剥茧地探寻这异常背后的秘密原因,并且一起琢磨琢磨怎么才能把它给妥妥地解决掉。 2. HessianRPC基础与工作原理 HessianRPC的核心在于对HTTP协议的运用以及Hessian二进制序列化机制。开发者只需要这么干,先定义一个接口,然后在这接口上,客户端和服务端两边各自整上实现,这样一来,远程方法调用就轻松搞定了。就像是你在家画好一张购物清单,然后分别让家人和超市那边按照清单准备东西,最后就能完成“远程”的物资调配啦。例如: java // 定义服务接口 public interface HelloService { String sayHello(String name); } // 服务端实现 @Service("helloService") public class HelloServiceImpl implements HelloService { @Override public String sayHello(String name) { return "Hello, " + name; } } // 客户端调用示例 HessianProxyFactory factory = new HessianProxyFactory(); HelloService service = (HelloService) factory.create(HelloService.class, "http://localhost:8080/hello"); String greeting = service.sayHello("World"); 3. HessianURLException详解 当我们在使用HessianRPC进行远程调用时,如果出现"HessianURLException: 创建或处理URL时发生错误。"异常,这通常意味着在创建或解析目标服务的URL地址时出现了问题。比如URL格式不正确、网络不可达或者其他相关的I/O异常。 java try { // 错误的URL格式导致HessianURLException HelloService wrongService = (HelloService) factory.create(HelloService.class, "localhost:8080/hello"); } catch (MalformedURLException e) { System.out.println("HessianURLException: 创建或处理URL时发生错误。"); // 抛出异常 } 在这个例子中,由于我们没有提供完整的URL(缺少协议部分"http://"),所以HessianRPC无法正确解析并创建到服务端的连接,从而抛出了HessianURLException。 4. 解决方案与预防措施 面对HessianURLException,我们需要从以下几个方面着手解决问题: 4.1 检查URL格式 确保提供的URL是完整且有效的,包括协议(如"http://"或"https://")、主机名、端口号及资源路径等必要组成部分。 java // 正确的URL格式 HelloService correctService = (HelloService) factory.create(HelloService.class, "http://localhost:8080/hello"); 4.2 确保网络可达性 检查客户端和服务端之间的网络连接是否畅通无阻。如果服务端未启动或者防火墙阻止了连接请求,也可能引发此异常。 4.3 异常捕获与处理 在代码中合理地处理此类异常,给用户提供明确的错误信息提示。 java try { HelloService service = (HelloService) factory.create(HelloService.class, "http://localhost:8080/hello"); } catch (HessianConnectionException | MalformedURLException e) { System.err.println("无法连接到远程服务,请检查URL和网络状况:" + e.getMessage()); } 5. 总结 在我们的编程旅程中,理解并妥善处理像"HessianURLException: 创建或处理URL时发生错误"这样的异常,有助于提升系统的稳定性和健壮性。对于HessianRPC来说,每一个细节都可能影响到远程调用的成功与否。所以呢,真要解决这类问题,归根结底就俩大法宝:一个是牢牢掌握的基础知识,那叫一个扎实;另一个就是严谨到家的编码习惯了,这两样可真是缺一不可的关键所在啊!伙计们,让我们一起瞪大眼睛,鼓起勇气,把HessianRPC变成我们手里的神兵利器,让它在开发分布式应用时,帮我们飞速提升效率,让开发过程更轻松、更给力!
2023-10-16 10:44:02
531
柳暗花明又一村
Nacos
...态的一致性。 java // 假设我们向Nacos添加一个服务实例 NamingService naming = NacosFactory.createNamingService("127.0.0.1:8848"); naming.registerInstance("my-service", "192.168.0.1", 8080); 上述代码中,当我们调用registerInstance方法注册一个服务实例时,这个操作会被Nacos集群以一种强一致的方式进行处理和存储。 3. Nacos的数据更新与同步机制 (1)数据变更通知:当Nacos中的数据发生变更时,它会通过长轮询或HTTP长连接等方式实时地将变更推送给订阅了该数据的客户端。例如: java ConfigService configService = NacosFactory.createConfigService("127.0.0.1:8848"); String content = configService.getConfig("my-config", "DEFAULT_GROUP", 5000); 在这个例子中,客户端会持续监听"my-config"的变更,一旦Nacos端的配置内容发生变化,客户端会立即得到通知并获取最新值。 (2)多数据中心同步:Nacos支持多数据中心部署模式,通过跨数据中心的同步策略,可以确保不同数据中心之间的数据一致性。当你在一个数据中心对数据做了手脚之后,这些改动会悄无声息地自动跑到其他数据中心去同步更新,确保所有地方的数据都保持一致,不会出现“各自为政”的情况。 4. 面对故障场景下的数据一致性保障 面对网络分区、节点宕机等异常情况,Nacos基于Raft算法构建的高可用架构能够有效应对。即使有几个家伙罢工了,剩下的大多数兄弟们还能稳稳地保证数据的读写操作照常进行。等那些暂时掉线的节点重新归队后,系统会自动自觉地把数据同步更新一遍,确保所有地方的数据都保持一致,一个字都不会差。 5. 结语 综上所述,Nacos凭借其严谨的设计理念和坚实的底层技术支撑,不仅在日常的服务管理和配置管理中表现卓越,更在复杂多变的分布式环境中展现出强大的数据一致性保证能力。了解并熟练掌握Nacos的数据一致性保障窍门,这绝对能让咱们在搭建和优化分布式系统时,不仅心里更有底气,还能实实在在地提升效率,像是给咱们的系统加上了强大的稳定器。每一次服务成功注册到Nacos,每一条配置及时推送到你们手中,这背后都是Nacos对数据一致性那份死磕到底的坚持和实实在在的亮眼表现。就像个超级小助手,时刻确保每个环节都精准无误,为你们提供稳稳的服务保障,这份功劳,Nacos可是功不可没!让我们一起,在探索和实践Nacos的过程中,感受这份可靠的力量!
2023-12-09 16:03:48
115
晚秋落叶
Sqoop
...M_OPTS="-Djavax.net.ssl.keyStore=/path/to/key.pem -Djavax.net.ssl.trustStore=/path/to/cert.pem" 这行代码将会告诉Java环境使用我们刚刚创建的key.pem文件作为私钥存储位置,以及使用cert.pem文件作为信任存储位置。 步骤3:重启Sqoop服务 最后,我们需要重启Sqoop服务以使新的配置生效。以下是一些常见的操作系统上启动和停止Sqoop服务的方法: Ubuntu/Linux: sudo service sqoop start sudo service sqoop stop CentOS/RHEL: sudo systemctl start sqoop.service sudo systemctl stop sqoop.service 四、总结 在本文中,我们介绍了如何配置Sqoop以使用SSL/TLS加密。你知道吗,就像给自家的保险箱装上密码锁一样,我们可以通过动手制作一个自签名的SSL证书,然后把它塞进Sqoop的配置文件里头。这样一来,就能像防护盾一样,把咱们的数据安全牢牢地守在中间人攻击的外面,让数据的安全性和隐私性蹭蹭地往上涨!虽然一开始可能会觉得有点烧脑,但仔细想想数据的价值,我们确实应该下点功夫,花些时间把这个事情搞定。毕竟,为了保护那些重要的数据,这点小麻烦又算得了什么呢? 当然,这只是基础的配置,如果我们需要更高级的保护,例如双重认证,我们还需要进行更多的设置。不管怎样,咱可得把数据安全当回事儿,要知道,数据可是咱们的宝贝疙瘩,价值连城的东西之一啊!
2023-10-06 10:27:40
184
追梦人-t
Dubbo
...巴巴开源的一个高性能Java RPC框架,一直备受青睐。不过嘛,在实际用起来的时候,服务一多啊,咱们就难免要跟分布式追踪系统打交道,各种问题接踵而至。这篇文章主要是想聊聊Dubbo怎么和Zipkin、Jaeger这些分布式追踪系统打交道,以及怎么优化它们的合作。我们会用一些真实的例子来说明,怎样才能更好地应对分布式追踪中遇到的各种问题。 1. 分布式追踪系统的重要性 首先,让我们来谈谈为什么需要分布式追踪系统。想想看,当你得照顾一大堆微服务组成的复杂系统时,每个请求都像是个大冒险,得穿梭在好几个服务之间打交道。在这种情况下,要准确地定位问题所在变得极其困难。而分布式追踪系统就像一双眼睛,能够帮助我们清晰地看到每一次请求的完整路径,包括它经过了哪些服务、耗时多少、是否有错误发生等关键信息。这对于提升系统性能、快速定位故障以及优化用户体验都至关重要。 2. Dubbo集成分布式追踪系统的初步探索 Dubbo本身并不直接支持分布式追踪功能,但可以通过集成第三方工具来实现这一目标。比如说Zipkin吧,这是Twitter推出的一个开源工具,专门用来追踪应用程序在分布式环境中的各种请求路径和数据流动情况。用它就像是给你的系统搭建了一个超级详细的导航地图,让你能一眼看清楚每个请求走过了哪些地方。接下来,我们将通过几个步骤来演示如何在Dubbo项目中集成Zipkin。 2.1 添加依赖 首先,我们需要向项目的pom.xml文件中添加Zipkin客户端的依赖。这步超级重要,因为得靠它让我们的Dubbo服务乖乖地把追踪信息发给Zipkin服务器,不然出了问题我们可找不到北啊。 xml io.zipkin.java zipkin-reporter-brave 2.7.5 2.2 配置Dubbo服务端 然后,在Dubbo服务端配置文件(如application.properties)中加入必要的配置项,让其知道如何连接到Zipkin服务器。 properties dubbo.application.qos-enable=false dubbo.registry.address=multicast://224.5.6.7:1234 指定Zipkin服务器地址 spring.zipkin.base-url=http://localhost:9411/ 使用Brave作为追踪库 brave.sampler.probability=1.0 这里,spring.zipkin.base-url指定了Zipkin服务器的URL,而brave.sampler.probability=1.0则表示所有请求都会被追踪。 2.3 编写服务接口与实现 假设我们有一个简单的服务接口,用于处理用户订单: java public interface OrderService { String placeOrder(String userId); } 服务实现类如下: java @Service("orderService") public class OrderServiceImpl implements OrderService { @Override public String placeOrder(String userId) { // 模拟业务逻辑 System.out.println("Order placed for user: " + userId); return "Your order has been successfully placed!"; } } 2.4 启动服务并测试 完成上述配置后,启动Dubbo服务端。你可以试试调用placeOrder这个方法,然后看看在Zipkin的界面上有没有出现相应的追踪记录。 3. 深入探讨 从Dubbo到Jaeger的转变 虽然Zipkin是一个优秀的解决方案,但在某些场景下,你可能会发现它无法满足你的需求。例如,如果你需要更高级别的数据采样策略或是对追踪数据有更高的控制权。这时,Jaeger就成为一个不错的选择。Jaeger是Uber开源的分布式追踪系统,它提供了更多的定制选项和更好的性能表现。 将Dubbo与Jaeger集成的过程与Zipkin类似,主要区别在于依赖库的选择和一些配置细节。这里就不详细展开,但你可以按照类似的思路去尝试。 4. 结语 持续优化与未来展望 集成分布式追踪系统无疑为我们的Dubbo服务增添了一双“慧眼”,使我们能够在复杂多变的分布式环境中更加从容不迫。然而,这只是一个开始。随着技术日新月异,咱们得不停地充电,学些新工具新技能,才能跟上这变化的脚步嘛。别忘了时不时地检查和调整你的追踪方法,确保它们跟得上你生意的发展步伐。 希望这篇文章能为你提供一些有价值的启示,让你在Dubbo与分布式追踪系统的世界里游刃有余。记住,每一次挑战都是成长的机会,勇敢地迎接它们吧!
2024-11-16 16:11:57
54
山涧溪流
SpringCloud
...能冒出来啦。 java @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { // 假设这里没有配置"/api/user"的路由,那么请求该路径就会出现404异常 return builder.routes() .route("product-service", r -> r.path("/api/product").uri("lb://PRODUCT-SERVICE")) .build(); } 2. 过滤器异常 Spring Cloud Gateway支持自定义过滤器,若过滤器内部逻辑错误或资源不足等,也可能引发异常。比如在开发权限校验过滤器的时候,假如咱们的验证逻辑不小心出了点小差错,就可能会让本来正常的请求被误判、给挡在外面了。 java @Component public class AuthFilter implements GlobalFilter, Ordered { @Override public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { // 假设这里的token解析或校验过程出现问题 String token = exchange.getRequest().getHeaders().getFirst("Authorization"); // ...省略校验逻辑... if (isValidToken(token)) { return chain.filter(exchange); } else { // 若返回错误信息时处理不当,可能导致异常 return exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED).buildMono(); } } // ... } 三、异常排查与解决策略 1. 路由匹配异常 : - 排查方法:首先检查路由配置是否正确且完整,确保所有接口都有对应的路由规则。 - 解决方案:添加或修复缺失或错误的路由规则。 2. 过滤器异常 : - 排查方法:通过日志定位到具体哪个过滤器报错,然后审查过滤器内部逻辑。对于自定义过滤器,应重点检查业务逻辑和资源管理部分。 - 解决方案:修复过滤器内部的逻辑错误,保证过滤器能够正确执行并返回预期结果。同时呢,千万记得要做好应对突发状况的工作,就像在过滤器里头万一出了岔子,咱们得确保能给客户端一个明明白白的反馈信息,而不是啥也不说就直接把异常抛出去,让请求咔嚓一下就断掉了。 四、总结与思考 面对Spring Cloud Gateway的异常情况,我们需要具备敏锐的问题洞察力和严谨的排查手段。每一个异常背后都可能是架构设计、资源配置、代码实现等方面的疏漏。所以呢,咱们在日常敲代码的时候,不仅要死磕代码质量,还得把Spring Cloud Gateway的运作机理摸得门儿清。这样一来,当问题突然冒出来的时候,就能快速找到“病灶”,手到病除地解决它。这样子,我们的微服务架构才能真正硬气起来,随时准备好迎接那些复杂多变、让人头疼的业务场景和挑战。 在实际开发中,每一次异常处理的过程都是我们深化技术认知,提升解决问题能力的良好契机。让我们一起在实战中不断积累经验,让Spring Cloud Gateway更好地服务于我们的微服务架构。
2023-07-06 09:47:52
95
晚秋落叶_
NodeJS
...V8引擎,专门用来跑JavaScript程序。这样一来,我们就能轻松愉快地在服务端搭建出各种实时应用,速度快得飞起,体验超级流畅!跟那些传统的后端语言,比如 PHP、Java 和 Ruby 不一样,Node.js 可厉害了,人家采用单线程模式,也就是说,所有的请求都由一条线程来处理,别看就一条线,但人家在处理并发请求时的身手可灵活了,性能杠杠滴! Node.js 提供了一个丰富的包管理器 npm,使得我们可以轻松地获取并安装各种第三方模块。另外,你知道吗,Node.js 社区那可是个百宝箱啊,里面装满了各种实用的框架和工具。就像Express.js、Koa.js这些服务端框架,还有Gulp.js、Webpack.js这些自动化构建工具,真是应有尽有。它们的存在,就是为了让我们能够更轻松、更快速地搭建起自己的应用程序,简直像是给开发者们插上了翅膀一样,特别给力! 在本篇文章中,我们将探讨如何使用 Node.js 进行云服务开发。首先,咱们得先摸清楚 Node.js 在云服务这个领域里头是怎么被用起来的,接下来再给大家伙儿逐一介绍一下时下热门的云服务提供商,还会附带上他们在 Node.js 开发这块的一些实用教程,让大家能更好地掌握上手。 一、Node.js 在云服务中的应用场景 1. 实时通信应用 Node.js 的事件驱动和非阻塞 I/O 模型使其非常适合实时通信应用。比如,我们完全可以借助 Socket.IO 这个神器,搭建出像实时聊天室、在线一起编辑文档这些超级实用的应用程序。就像是你和朋友们能即时聊天的小天地,或者大家一起同时修改同一份文档的神奇工具,这些都是 Socket.IO 能帮我们实现的好玩又强大的功能。 2. 后端服务 由于 Node.js 具有高并发性和异步编程的能力,因此它可以作为后端服务的核心引擎。比如,咱们可以拿 Express.js 这个框架来搭建一个飞快的 RESTful API,要不就用 Koa.js 来整一个更轻巧灵活的服务器,随你喜欢。 3. 数据库中间件 Node.js 可以作为数据库中间件,与数据库交互并实现数据的读取、存储和更新等功能。比如,我们可以拿起 Mongoose ORM 这个工具箱,它能帮我们牵线搭桥连上 MongoDB 数据库。然后,我们就能够借助它提供的查询语句,像玩魔术一样对数据进行各种操作,插入、删除、修改,随心所欲。 二、常用的云服务提供商及其 Node.js 开发教程 1. AWS AWS 提供了一系列的云服务,包括计算、存储、数据库、安全等等。在 AWS 上,我们可以使用 Lambda 函数来实现无服务器架构,使用 EC2 或 ECS 来部署 Node.js 应用程序。此外,AWS 还提供了丰富的 SDK 和 CLI 工具,方便我们在本地开发和调试应用程序。 2. Google Cloud Platform (GCP) GCP 提供了类似的云服务,包括 Compute Engine、App Engine、Cloud Functions、Cloud SQL 等等。在 GCP(Google Cloud Platform)这个平台上,咱们完全可以利用 Node.js 这门技术来开发应用程序,然后把它们稳稳地部署到 App Engine 上。这样一来,咱们就能更轻松、更方便地管理自家的应用程序,同时还能对它进行全方位的监控,确保一切运行得妥妥当当的。就像是在自家后院种菜一样,从播种(开发)到上架(部署),再到日常照料(管理和监控),全都在掌控之中。 3. Azure Azure 是微软提供的云服务平台,支持多种编程语言和技术栈。在 Azure 上,我们可以使用 Function App 来部署 Node.js 函数,并使用 App Service 来部署完整的 Node.js 应用程序。另外,Azure还准备了一整套超级实用的DevOps工具和服务,这对我们来说可真是个大宝贝,能够帮我们在管理和发布应用程序时更加得心应手,轻松高效。 接下来,我们将详细介绍如何使用 Node.js 在 AWS Lambda 上构建无服务器应用程序。 三、在 AWS Lambda 上使用 Node.js 构建无服务器应用程序 AWS Lambda 是一种无服务器计算服务,可以让开发者无需关心服务器的操作系统、虚拟机配置等问题,只需要专注于编写和上传代码即可。在Lambda这个平台上,咱们能够用Node.js来编写函数,就像变魔术一样把函数和触发器手牵手连起来,这样一来,就能轻松实现自动执行的酷炫效果啦! 以下是使用 Node.js 在 AWS Lambda 上构建无服务器应用程序的基本步骤: Step 1: 创建 AWS 帐户并登录 AWS 控制台 Step 2: 安装 AWS CLI 工具 Step 3: 创建 Lambda 函数 Step 4: 编写 Lambda 函数 Step 5: 配置 Lambda 函数触发器 Step 6: 测试 Lambda 函数 Step 7: 将 Lambda 函数部署到生产环境
2024-01-24 17:58:24
144
青春印记-t
Spark
...供了多种API,包括Java、Scala、Python等,非常灵活易用。 2.2 Kafka简介 Kafka,全名Apache Kafka,是一个分布式的消息系统,主要用来处理实时数据流。这个东西特别能扛,能存好多数据,还不容易丢,用来搭建实时的数据流和应用再合适不过了。 2.3 Spark与Kafka集成的优势 - 实时处理:Spark可以实时处理Kafka中的数据。 - 灵活性:Spark支持多种编程语言,Kafka则提供丰富的API接口,两者结合让开发更加灵活。 - 高吞吐量:Spark的并行处理能力和Kafka的高吞吐量相结合,能够高效处理大规模数据流。 3. 实战准备 在开始之前,你需要先准备好环境。确保你的机器上已经安装了Java、Scala以及Spark。说到Kafka,你可以直接下载安装包,或者用Docker容器搞一个本地环境,超级方便!我推荐你用Docker,因为它真的超简单方便,还能随手搞出好几个实例来测试,特别实用。 bash 安装Docker sudo apt-get update sudo apt-get install docker.io 拉取Kafka镜像 docker pull wurstmeister/kafka 启动Kafka容器 docker run -d --name kafka -p 9092:9092 -e KAFKA_ADVERTISED_HOST_NAME=localhost wurstmeister/kafka 4. 集成实战 4.1 创建Kafka主题 首先,我们需要创建一个Kafka主题,以便后续的数据流能够被正确地发送和接收。 bash 进入容器 docker exec -it kafka /bin/bash 创建主题 kafka-topics.sh --create --topic test-topic --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 4.2 发送数据到Kafka 接下来,我们可以编写一个简单的脚本来向Kafka的主题中发送一些数据。这里我们使用Python的kafka-python库来实现。 python from kafka import KafkaProducer producer = KafkaProducer(bootstrap_servers='localhost:9092') for _ in range(10): message = "Hello, Kafka!".encode('utf-8') producer.send('test-topic', value=message) print("Message sent:", message.decode('utf-8')) producer.flush() producer.close() 4.3 使用Spark读取Kafka数据 现在,我们来编写一个Spark程序,用于读取刚才发送到Kafka中的数据。这里我们使用Spark的Structured Streaming API。 scala import org.apache.spark.sql.SparkSession val spark = SparkSession.builder.appName("SparkKafkaIntegration").getOrCreate() val df = spark.readStream .format("kafka") .option("kafka.bootstrap.servers", "localhost:9092") .option("subscribe", "test-topic") .load() val query = df.selectExpr("CAST(value AS STRING)") .writeStream .outputMode("append") .format("console") .start() query.awaitTermination() 这段代码会启动一个Spark应用程序,从Kafka的主题中读取数据,并将其打印到控制台。 4.4 实时处理 接下来,我们可以在Spark中对数据进行实时处理。例如,我们可以统计每秒钟接收到的消息数量。 scala import org.apache.spark.sql.functions._ val countDF = df.selectExpr("CAST(value AS STRING)") .withWatermark("timestamp", "1 minute") .groupBy( window($"timestamp", "1 minute"), $"value" ).count() val query = countDF.writeStream .outputMode("complete") .format("console") .start() query.awaitTermination() 这段代码会在每分钟的时间窗口内统计消息的数量,并将其输出到控制台。 5. 总结与反思 通过这次实战,我们成功地将Spark与Kafka进行了集成,并实现了数据的实时处理。虽然过程中遇到了一些挑战,但最终还是顺利完成了任务。这个经历让我明白,书本上的知识和实际动手做真是两码事。不一次次去试,根本没法真正搞懂怎么用这门技术。希望这次分享对你有所帮助,也期待你在实践中也能有所收获! 如果你有任何问题或想法,欢迎随时交流讨论。
2025-03-08 16:21:01
76
笑傲江湖
转载文章
...bectl get services --namespace=kube-system 如果Heapster服务正在运行,会有如下输出: NAMESPACE NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGEkube-system heapster 10.11.240.9 <none> 80/TCP 6d 创建一个命名空间 创建命名空间,以便你在实验中创建的资源可以从集群的资源中隔离出来。 kubectl create namespace mem-example 配置内存申请和限制 给容器配置内存申请,只要在容器的配置文件里添加resources:requests就可以了。配置限制的话, 则是添加resources:limits。 本实验,我们创建包含一个容器的Pod,这个容器申请100M的内存,并且内存限制设置为200M,下面 是配置文件: memory-request-limit.yaml apiVersion: v1kind: Podmetadata:name: memory-demospec:containers:- name: memory-demo-ctrimage: vish/stressresources:limits:memory: "200Mi"requests:memory: "100Mi"args:- -mem-total- 150Mi- -mem-alloc-size- 10Mi- -mem-alloc-sleep- 1s 在这个配置文件里,args代码段提供了容器所需的参数。-mem-total 150Mi告诉容器尝试申请150M 的内存。 创建Pod: kubectl create -f https://k8s.io/docs/tasks/configure-pod-container/memory-request-limit.yaml --namespace=mem-example 验证Pod的容器是否正常运行: kubectl get pod memory-demo --namespace=mem-example 查看Pod的详细信息: kubectl get pod memory-demo --output=yaml --namespace=mem-example 这个输出显示了Pod里的容器申请了100M的内存和200M的内存限制。 ...resources:limits:memory: 200Mirequests:memory: 100Mi... 启动proxy以便我们可以访问Heapster服务: kubectl proxy 在另外一个命令行窗口,从Heapster服务获取内存使用情况: curl http://localhost:8001/api/v1/proxy/namespaces/kube-system/services/heapster/api/v1/model/namespaces/mem-example/pods/memory-demo/metrics/memory/usage 这个输出显示了Pod正在使用162,900,000字节的内存,大概就是150M。这很明显超过了申请 的100M,但是还没达到200M的限制。 {"timestamp": "2017-06-20T18:54:00Z","value": 162856960} 删除Pod: kubectl delete pod memory-demo --namespace=mem-example 超出容器的内存限制 只要节点有足够的内存资源,那容器就可以使用超过其申请的内存,但是不允许容器使用超过其限制的 资源。如果容器分配了超过限制的内存,这个容器将会被优先结束。如果容器持续使用超过限制的内存, 这个容器就会被终结。如果一个结束的容器允许重启,kubelet就会重启他,但是会出现其他类型的运行错误。 本实验,我们创建一个Pod尝试分配超过其限制的内存,下面的这个Pod的配置文档,它申请50M的内存, 内存限制设置为100M。 memory-request-limit-2.yaml apiVersion: v1kind: Podmetadata:name: memory-demo-2spec:containers:- name: memory-demo-2-ctrimage: vish/stressresources:requests:memory: 50Milimits:memory: "100Mi"args:- -mem-total- 250Mi- -mem-alloc-size- 10Mi- -mem-alloc-sleep- 1s 在配置文件里的args段里,可以看到容器尝试分配250M的内存,超过了限制的100M。 创建Pod: kubectl create -f https://k8s.io/docs/tasks/configure-pod-container/memory-request-limit-2.yaml --namespace=mem-example 查看Pod的详细信息: kubectl get pod memory-demo-2 --namespace=mem-example 这时候,容器可能会运行,也可能会被杀掉。如果容器还没被杀掉,重复之前的命令直至 你看到这个容器被杀掉: NAME READY STATUS RESTARTS AGEmemory-demo-2 0/1 OOMKilled 1 24s 查看容器更详细的信息: kubectl get pod memory-demo-2 --output=yaml --namespace=mem-example 这个输出显示了容器被杀掉因为超出了内存限制。 lastState:terminated:containerID: docker://65183c1877aaec2e8427bc95609cc52677a454b56fcb24340dbd22917c23b10fexitCode: 137finishedAt: 2017-06-20T20:52:19Zreason: OOMKilledstartedAt: null 本实验里的容器可以自动重启,因此kubelet会再去启动它。输入多几次这个命令看看它是怎么 被杀掉又被启动的: kubectl get pod memory-demo-2 --namespace=mem-example 这个输出显示了容器被杀掉,被启动,又被杀掉,又被启动的过程: stevepe@sperry-1:~/steveperry-53.github.io$ kubectl get pod memory-demo-2 --namespace=mem-exampleNAME READY STATUS RESTARTS AGEmemory-demo-2 0/1 OOMKilled 1 37sstevepe@sperry-1:~/steveperry-53.github.io$ kubectl get pod memory-demo-2 --namespace=mem-exampleNAME READY STATUS RESTARTS AGEmemory-demo-2 1/1 Running 2 40s 查看Pod的历史详细信息: kubectl describe pod memory-demo-2 --namespace=mem-example 这个输出显示了Pod一直重复着被杀掉又被启动的过程: ... Normal Created Created container with id 66a3a20aa7980e61be4922780bf9d24d1a1d8b7395c09861225b0eba1b1f8511... Warning BackOff Back-off restarting failed container 查看集群里节点的详细信息: kubectl describe nodes 输出里面记录了容器被杀掉是因为一个超出内存的状况出现: Warning OOMKilling Memory cgroup out of memory: Kill process 4481 (stress) score 1994 or sacrifice child 删除Pod: kubectl delete pod memory-demo-2 --namespace=mem-example 配置超出节点能力范围的内存申请 内存的申请和限制是针对容器本身的,但是认为Pod也有容器的申请和限制是一个很有帮助的想法。 Pod申请的内存就是Pod里容器申请的内存总和,类似的,Pod的内存限制就是Pod里所有容器的 内存限制的总和。 Pod的调度策略是基于请求的,只有当节点满足Pod的内存申请时,才会将Pod调度到合适的节点上。 在这个实验里,我们创建一个申请超大内存的Pod,超过了集群里任何一个节点的可用内存资源。 这个容器申请了1000G的内存,这个应该会超过你集群里能提供的数量。 memory-request-limit-3.yaml apiVersion: v1kind: Podmetadata:name: memory-demo-3spec:containers:- name: memory-demo-3-ctrimage: vish/stressresources:limits:memory: "1000Gi"requests:memory: "1000Gi"args:- -mem-total- 150Mi- -mem-alloc-size- 10Mi- -mem-alloc-sleep- 1s 创建Pod: kubectl create -f https://k8s.io/docs/tasks/configure-pod-container/memory-request-limit-3.yaml --namespace=mem-example 查看Pod的状态: kubectl get pod memory-demo-3 --namespace=mem-example 输出显示Pod的状态是Pending,因为Pod不会被调度到任何节点,所有它会一直保持在Pending状态下。 kubectl get pod memory-demo-3 --namespace=mem-exampleNAME READY STATUS RESTARTS AGEmemory-demo-3 0/1 Pending 0 25s 查看Pod的详细信息包括事件记录 kubectl describe pod memory-demo-3 --namespace=mem-example 这个输出显示容器不会被调度因为节点上没有足够的内存: Events:... Reason Message------ -------... FailedScheduling No nodes are available that match all of the following predicates:: Insufficient memory (3). 内存单位 内存资源是以字节为单位的,可以表示为纯整数或者固定的十进制数字,后缀可以是E, P, T, G, M, K, Ei, Pi, Ti, Gi, Mi, Ki.比如,下面几种写法表示相同的数值:alue: 128974848, 129e6, 129M , 123Mi 删除Pod: kubectl delete pod memory-demo-3 --namespace=mem-example 如果不配置内存限制 如果不给容器配置内存限制,那下面的任意一种情况可能会出现: 容器使用内存资源没有上限,容器可以使用当前节点上所有可用的内存资源。 容器所运行的命名空间有默认内存限制,容器会自动继承默认的限制。集群管理员可以使用这个文档 LimitRange来配置默认的内存限制。 内存申请和限制的原因 通过配置容器的内存申请和限制,你可以更加有效充分的使用集群里内存资源。配置较少的内存申请, 可以让Pod跟任意被调度。设置超过内存申请的限制,可以达到以下效果: Pod可以在负载高峰时更加充分利用内存。 可以将Pod的内存使用限制在比较合理的范围。 清理 删除命名空间,这会顺便删除命名空间里的Pod。 kubectl delete namespace mem-example 译者:NickSu86 原文链接 本篇文章为转载内容。原文链接:https://blog.csdn.net/Aria_Miazzy/article/details/99694937。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-23 12:14:07
494
转载
转载文章
...du.edu.cn/Service/tips/zhcon_manual.html zhcon下载连接: http://zhcon.gnuchina.org/download/...on-0.2.1.tar.gz 十三.问:我在安装一个软件的时候,提示我缺少一个.so文件,安装无法继续,怎么办? 答:.so文件就像windows中的.dll文件一样,是库文件。一个程序的正常安装和运行需要特定的库文件的支持。所以你需要去找到包含这个.so的包装上。去 http://www.rpmfind.net用你缺的那个.....剿枰?rpm包 十四.我访问windows分区时发现所有windows分区中的文件和文件夹名中的中文全变成问号,怎么办? 答:在第三贴中我们讲解了通过编辑/etc/fstab实现在linux中访问windows的fat32分区。同样,我们可以通过进一步修改 /etc/fstab来实现中文文件名显示。只要把/dev/hda1 /mnt/c vfat default 0 0中的default全改为iocharset=cp936就行了。 十五.我的rh8.0中的XMMS不好使,不能播放MP3,怎么办? 答:这是因为rh公司怕别人告他侵权,所以在rh8.0中去掉了XMMS对MP3的支持,8.0以前的版本都是好使的。在8.0中要解决也很简单,装一个插件就行了。这个插件我放在本贴的附件里,rpm格式,经winrar压缩 附件: http://www.chinalinuxpub.com/vbbfor...s=&postid=86299 十六.问:我在linux中怎样才能使用windows分区呢? 答:先说一点背景知识。linux支持很多种文件系统,包括windows的fat32和ntfs。对fat32的支持已经很好,可以直接使用,而对ntfs 的支持还不是太好,只能读,而写是极危险的,并且对ntfs的支持不是默认的,也就是说你想要使用ntfs的话,需要重新编译内核。鉴于重编内核对于新手的复杂性,这里只讲解使用fat32分区的方法下面给出上述问题的两种解决方案:1.在安装系统(linux),进行到分区选择挂载点时,你可以建立几个挂载点,如/mnt/c,/mnt/d等,然后选择你的windows fat32分区,把它们分别挂载到前面建立的挂载点即可。(注意,正如前面所说,在这里你不能把一个ntfs分区挂载到一个挂载点,应为ntfs不是默认支持的。)这样你装好系统后就能直接使用你的windows fat32分区了。例如,你把windows的c盘(linux中的/dev/hda1)挂载到/mnt/c,那么你就能在/mnt/c目录中找到你的c 盘中的全部数据。2. 如果你在安装系统时没有像方案1所说的那样挂载上你的fat32分区,没关系,仍然能够很方便的解决这个问题。首先,用一个文本编辑器(如vi)打开 /etc/fstab,在文件的最后加入类似如下的几行 /dev/hda1 /mnt/c vfat default 0 0 你所要做的修改就是,把/dev/hda1改成你要挂载的fat32分区在linux中的设备号,把/mnt/c改成相应的挂载点即可。注意,挂载点就是一个目录,这个目录要事先建立。举一个例子,我有三个fat32分区,在windows中是c,d,e盘,在linux中的设备号分别为 /dev/hda1,/dev/hda5,/dev/hda6。那么我就要先建立3个挂载点,如/mnt/c,/mnt/d,/mnt/e,然后在 /etc/fstab中加上这么几行: /dev/hda1 /mnt/c vfat default 0 0 /dev/hda5 /mnt/d vfat default 0 0 /dev/hda6 /mnt/e vfat default 0 0 保存一下退出编辑器。这样以后你重启机器后就能直接使用c,d,e这三个fat32格式的windows分区了 十七.问:我的机器重装windows后,开机启动就直接进入了windows,原来的linux进不去了,怎么办? 答:这是由于windows的霸道。重装windows后,windows重写了你的mbr,覆盖掉了grub。解决方法很简单:用你的linux第一张安装盘引导进入linx rescue模式(如何进入?你注意一下系统的提示信息就知道了),执行下面两条命令就可以了 chroot /mnt/sysimage 改变你的根目录 grub-install /dev/hda 安装grub到mbr 十八.问:我的linux开机直接进入文本界面,怎样才能让它默认进入图形界面? 答:修改/etc/inittab文件,其中有一行id:3:initdefault,意思是说开机默认进入运行级别3(多用户的文本界面),把它改成id:5:initdefault,既开机默认进入运行级别5(多用户的图形界面)。这样就行了。 十九.如何同时启动多个x 以前的帖子,估计很多人没看过,贴出来温习一下 Linux里的X-Windows以其独特的面貌和强大的功能吸引了很多原先对linux不感兴趣的人,特别是KDE和GNOME,功能强大不说,而且自带了很多很棒的软件,界面非常友好,很适合于初学者。下面告诉大家一个同时启动6个X的小技巧: 在~/.bashrc中加入 以下几行: alias X=startx -- -bpp 32 -quiet& alias X1=startx -- :1 -bpp 32 -quiet& alias X2=startx -- :2 -bpp 32 -quiet& alias X3=startx -- :3 -bpp 32 -quiet& alias X4=startx -- :4 -bpp 32 -quiet& alias X5=startx -- :5 -bpp 32 -quiet& 其中32是显示器的色彩深度,你应该根据自己的实际情况设置。 之后运行 bash 使改变生效,以后只要依次运行X,X1,X2,X3,X4,X5就可以启动6个X-Windows了。 二十.装了rpm的postgresql之后启动 /etc/init.d/postgresql start 是不能启动postgresql的tcp/ip连接支持的,所以打开/etc/init.d/postgresql这个文件把 su -l postgres -s /bin/sh -c "/usr/bin/pg_ctl -D $PGDATA -p /usr/bin/postmaster start > /dev/null 2>&1" < /dev/null 改为: su -l postgres -s /bin/sh -c "/usr/bin/pg_ctl -o -o -F -i -w -D $PGDATA -p /usr/bin/postmaster start > /dev/null 2>&1" < /dev/null 这样就可以启动数据库的tcp/ip链接了 二十一.如何将man转存为文本文件 以ls的man为例 man ls |col -b >ls.txt 将info变成文本,以make为例 info make -o make.txt -s 二十二.如何在文本模式下发送2进制文件 首先检查系统有没有uuencode 和 uudecode如果没有从光盘上装 rpm -ivh sharutils-x.xx.x-x.rpm 假设要发送的文件是vpopmail-5.2.1.tar.gz执行 uuencode -m vpopmail-5.2.1.tar.gz vpopmail.tar.gz>encodefile 说明: uuenode是编码命令,-m是使用mime64编码,vpopmail-5.2.1.tar.gz是要编码的文件,vpopmail.tar.gz是如果解码后得到的文件名,encodefile是编码后的文件名。 执行上述命令之后就可以通过mail命令发送编码后的文件了 mail chenlf@chinalinuxpub.com<encodefile 好了,现在我来接收邮件 在控制台上输入mail命令: mail Mail version 8.1 6/6/93. Type ? for help. "/var/spool/mail/chenlf": 2 messages 2 new >N 1 chenlf@ns1.catv.net Mon Jun 10 16:44 17/363 N 2 root@ns2.catv.net Mon Jun 10 16:45 6091/371145 & 2 Message 2: From root@ns2.catv.net Mon Jun 10 16:45:28 2002 Date: Mon, 10 Jun 2002 16:44:51 +0800 From: root <root@ns2.catv.net> To: chenlf@chinalinuxpub.com begin-base64 644 vpopmai.tar.gz H4sIABr15TwAA+w9a2PbNpL7NfwVqNPbWIlFPSzbiR2n9SuxE7/OcuLNtdmU EiGLMUWqfFhWt7u//eYBgKRE2U7iTa+3VndjiQQGg5nBYDAYDC6H4XDgeH51 yW7ajdpf/h2fer1VX1lagr/1+spyq/BXff5SX2mtNBZXmovN5l/qjWZrqfEX sfRvwWbik8aJEwnxl7ifDofXlLvp/Z/0c1nk/8uN/777NuqNen251ZrB/+XF pcUG8r/ZbC0vL9ZXoPwi/O8von73qEx//sP5bwHHxanT8aUIe2IrDBIZJLFl 7QVJFFovpZOkkYxFL4yEFhVLCKhk1W2xG45E1wnEnohlIsJAiksvSlLHF24I JQORhKIjRdKXYhh5Ayca6xcAD8DQm4HT7XuB/EGcSXgbPErEyAkSrNp3LqVw grGoyaRbGzpxPHJFGssotq0Gtw6l9gTgJbixode9EOlQDMaTmEjE/AerydVc rAY4jJzIFY7vC3wL2DgJvJIxIjFwkm6fWkfw1KoAIti/EgkWc3A6YRp05ReB aeXAQH34GoXOwAvOVUnoEnwRYRqJeJAMgczRpYzEyEv6YQoUH8oACltLtjjD Rr1YOCJ2BkPgJop1IuJu5A0TYh9xIdQwfrCWTdt9pMKvaZg4j5jT3PgojC5+ sFZswM0LAJzvSyhGXQSCOmLoO9DtEOAicBCD2qUT1agAg44BSd+1niIEzVPs ................. ................. ................. & s 2 encodefile "encode" [New file] & q 然后进行解码 uudecode encodefile ls encodefile vpopmai.tar.gz tar zxvf vpopmail.tar.gz OK了 二十三.将 man page 转成 HTML 格式 使用 man2html 这个指令,就可以将 man page 转成 HTML 格式了。用法是: man2html filename > htmlfile.html 二十四.如何在gnome和kde之间切换。 如果你是以图形登录方式登录linux,那么点击登录界面上的session(任务)即可以选择gnome和kde。如果你是以文本方式登录,那执行switchdesk gnome或switchdesk kde,然后再startx就可以进入gnome或kde。 25...tar,.tar.gz,.bz2,.tar.bz2,.bz,.gz是什么文件,如何解开他们? 他们都是文件(压缩)包。 .tar:把文件打包,不压缩:tar cvf .tar dirName 解开:tar xvf .tar .tar.gz:把文件打包并压缩:tar czvf .tar.gz dirName 解开:tar xzvf .tar.gz .bz2:解开:bzip2 -d .bz2 .bz:解开:bzip -d .bz .gz:解开:gzip -d .gz 26.linux下如何解开.zip,.rar压缩文件? rh8下有一个图形界面的软件file-roller可以做这件事。令外可以用unzip .zip解开zip文件,unrar .rar解开rar文件,不过unrar一般系统不自带,要到网上下载。 27.linux下如何浏览.iso光盘镜像文件? a.建一个目录,如:mkdir a b.把iso文件挂载到该目录上:mount -o loop xxxx.iso a 现在目录a里的内容就是iso文件里的内容了。 28.linux下如何配置网络? 用netconfig。“IP address:”就是要配置的IP地址,“Netmask:”子网掩码,“Default gateway (IP):”网关,“Primary nameserver:”DNS服务器IP。 29.如何让鼠标支持滚轮? 在配置鼠标时,选择微软的鼠标,并正确选择端口如ps2,usb等 30.如何让控制台支持中文显示? 安装zhcon。zhcon需要libimm_server.so和libpth.so.13这两个库支持。一般的中文输入法应该都有libimm_server.so。libpth.so.13出自pth-1.3.x。把这两个文件放到/usr/lib下就行了。 31.如何配置grub? 修改/boot/grub/grub.conf文件。其中 “default=n”(n是个数字)是grub引导菜单默认被选中的项,n从0开始,0表示第一项,1表示第二项,依此类推。 “timeout=x”(x是一个数)是超时时间,单位是妙。也就是引导菜单显示后,如果x秒内用户不进行选择,那么grub将启动默认项。 “splashimage =xxxxxx”,这是引导菜单的背景图,先不理他。 其它常用项我用下面的例子来说明: title Red Hat 8.0 root (hd1,6) kernel /boot/vmlinuz-2.4.18-14 ro root=/dev/hdb7 initrd /boot/initrd-2.4.18-14.img 其中"Red Hat 8.0"是在启动菜单列表里显示的名字 root (hdx,y)用来指定你的boot分区位置,如果你没有分boot分区(本例就没分boot分区),那就指向根分区就行了,hdx是linux所在硬盘,hd0是第一块硬盘,hd1是第二块,依此类推。y是分区位置,从0开始,也就是等于分区号减一,比如你要指向的分区是hdx7,那么y就是6,如果是hdx1,那y就是0。注意root后面要有一个空格。 kernel /boot/vmlinuz-2.4.18-14,其中"/boot/vmlinuz-2.4.18-14"是你要用的内核路径,如果你编译了心内核,把它改成你的新内核的路径就行了。 ro就不用管,写上不会有错。 root=/dev/hdxx指定根分区,本例是hdb7,所以root=/dev/hdb7 initrd xxxxxxxxxxxxx这行不要也行,目前我还不清楚它是做什么用的。 上面是linux的,下面是windows的 title windows 98 rootnoverify (hd0,0) chainloader +1 title xxxxxxx不用解释了,上面有解释。 rootnoverify (hdx,y)用来指定windows所在分区,x,y跟上面一样,注意rootnoverify后有空格。 chainloader +1照抄就行,注意空格。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gudulyn/article/details/764890。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-27 09:27:49
255
转载
转载文章
...this help message and exit-d [DELIM], --delimiter [DELIM]use DELIM instead of ' / ' for word delimiter; or aspace if it is used without DELIM-p [DELIM], --pos [DELIM]enable POS tagging; if DELIM is specified, use DELIMinstead of '_' for POS delimiter-D DICT, --dict DICT use DICT as dictionary-u USER_DICT, --user-dict USER_DICTuse USER_DICT together with the default dictionary orDICT (if specified)-a, --cut-all full pattern cutting (ignored with POS tagging)-n, --no-hmm don't use the Hidden Markov Model-q, --quiet don't print loading messages to stderr-V, --version show program's version number and exitIf no filename specified, use STDIN instead. 延迟加载机制 jieba 采用延迟加载,import jieba 和 jieba.Tokenizer() 不会立即触发词典的加载,一旦有必要才开始加载词典构建前缀字典。如果你想手工初始 jieba,也可以手动初始化。 import jiebajieba.initialize() 手动初始化(可选) 在 0.28 之前的版本是不能指定主词典的路径的,有了延迟加载机制后,你可以改变主词典的路径: jieba.set_dictionary('data/dict.txt.big') 例子: https://github.com/fxsjy/jieba/blob/master/test/test_change_dictpath.py 其他词典 占用内存较小的词典文件 https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.small 支持繁体分词更好的词典文件 https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.big 下载你所需要的词典,然后覆盖 jieba/dict.txt 即可;或者用 jieba.set_dictionary('data/dict.txt.big') 其他语言实现 结巴分词 Java 版本 作者:piaolingxue 地址:https://github.com/huaban/jieba-analysis 结巴分词 C++ 版本 作者:yanyiwu 地址:https://github.com/yanyiwu/cppjieba 结巴分词 Rust 版本 作者:messense, MnO2 地址:https://github.com/messense/jieba-rs 结巴分词 Node.js 版本 作者:yanyiwu 地址:https://github.com/yanyiwu/nodejieba 结巴分词 Erlang 版本 作者:falood 地址:https://github.com/falood/exjieba 结巴分词 R 版本 作者:qinwf 地址:https://github.com/qinwf/jiebaR 结巴分词 iOS 版本 作者:yanyiwu 地址:https://github.com/yanyiwu/iosjieba 结巴分词 PHP 版本 作者:fukuball 地址:https://github.com/fukuball/jieba-php 结巴分词 .NET(C) 版本 作者:anderscui 地址:https://github.com/anderscui/jieba.NET/ 结巴分词 Go 版本 作者: wangbin 地址: https://github.com/wangbin/jiebago 作者: yanyiwu 地址: https://github.com/yanyiwu/gojieba 结巴分词Android版本 作者 Dongliang.W 地址:https://github.com/452896915/jieba-android 友情链接 https://github.com/baidu/lac 百度中文词法分析(分词+词性+专名)系统 https://github.com/baidu/AnyQ 百度FAQ自动问答系统 https://github.com/baidu/Senta 百度情感识别系统 系统集成 Solr: https://github.com/sing1ee/jieba-solr 分词速度 1.5 MB / Second in Full Mode 400 KB / Second in Default Mode 测试环境: Intel® Core™ i7-2600 CPU @ 3.4GHz;《围城》.txt 常见问题 1. 模型的数据是如何生成的? 详见: https://github.com/fxsjy/jieba/issues/7 2. “台中”总是被切成“台 中”?(以及类似情况) P(台中) < P(台)×P(中),“台中”词频不够导致其成词概率较低 解决方法:强制调高词频 jieba.add_word('台中') 或者 jieba.suggest_freq('台中', True) 3. “今天天气 不错”应该被切成“今天 天气 不错”?(以及类似情况) 解决方法:强制调低词频 jieba.suggest_freq(('今天', '天气'), True) 或者直接删除该词 jieba.del_word('今天天气') 4. 切出了词典中没有的词语,效果不理想? 解决方法:关闭新词发现 jieba.cut('丰田太省了', HMM=False) jieba.cut('我们中出了一个叛徒', HMM=False) 更多问题请点击:https://github.com/fxsjy/jieba/issues?sort=updated&state=closed 修订历史 https://github.com/fxsjy/jieba/blob/master/Changelog jieba “Jieba” (Chinese for “to stutter”) Chinese text segmentation: built to be the best Python Chinese word segmentation module. Features Support three types of segmentation mode: Accurate Mode attempts to cut the sentence into the most accurate segmentations, which is suitable for text analysis. Full Mode gets all the possible words from the sentence. Fast but not accurate. Search Engine Mode, based on the Accurate Mode, attempts to cut long words into several short words, which can raise the recall rate. Suitable for search engines. Supports Traditional Chinese Supports customized dictionaries MIT License Online demo http://jiebademo.ap01.aws.af.cm/ (Powered by Appfog) Usage Fully automatic installation: easy_install jieba or pip install jieba Semi-automatic installation: Download http://pypi.python.org/pypi/jieba/ , run python setup.py install after extracting. Manual installation: place the jieba directory in the current directory or python site-packages directory. import jieba. Algorithm Based on a prefix dictionary structure to achieve efficient word graph scanning. Build a directed acyclic graph (DAG) for all possible word combinations. Use dynamic programming to find the most probable combination based on the word frequency. For unknown words, a HMM-based model is used with the Viterbi algorithm. Main Functions Cut The jieba.cut function accepts three input parameters: the first parameter is the string to be cut; the second parameter is cut_all, controlling the cut mode; the third parameter is to control whether to use the Hidden Markov Model. jieba.cut_for_search accepts two parameter: the string to be cut; whether to use the Hidden Markov Model. This will cut the sentence into short words suitable for search engines. The input string can be an unicode/str object, or a str/bytes object which is encoded in UTF-8 or GBK. Note that using GBK encoding is not recommended because it may be unexpectly decoded as UTF-8. jieba.cut and jieba.cut_for_search returns an generator, from which you can use a for loop to get the segmentation result (in unicode). jieba.lcut and jieba.lcut_for_search returns a list. jieba.Tokenizer(dictionary=DEFAULT_DICT) creates a new customized Tokenizer, which enables you to use different dictionaries at the same time. jieba.dt is the default Tokenizer, to which almost all global functions are mapped. Code example: segmentation encoding=utf-8import jiebaseg_list = jieba.cut("我来到北京清华大学", cut_all=True)print("Full Mode: " + "/ ".join(seg_list)) 全模式seg_list = jieba.cut("我来到北京清华大学", cut_all=False)print("Default Mode: " + "/ ".join(seg_list)) 默认模式seg_list = jieba.cut("他来到了网易杭研大厦")print(", ".join(seg_list))seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造") 搜索引擎模式print(", ".join(seg_list)) Output: [Full Mode]: 我/ 来到/ 北京/ 清华/ 清华大学/ 华大/ 大学[Accurate Mode]: 我/ 来到/ 北京/ 清华大学[Unknown Words Recognize] 他, 来到, 了, 网易, 杭研, 大厦 (In this case, "杭研" is not in the dictionary, but is identified by the Viterbi algorithm)[Search Engine Mode]: 小明, 硕士, 毕业, 于, 中国, 科学, 学院, 科学院, 中国科学院, 计算, 计算所, 后, 在, 日本, 京都, 大学, 日本京都大学, 深造 Add a custom dictionary Load dictionary Developers can specify their own custom dictionary to be included in the jieba default dictionary. Jieba is able to identify new words, but you can add your own new words can ensure a higher accuracy. Usage: jieba.load_userdict(file_name) file_name is a file-like object or the path of the custom dictionary The dictionary format is the same as that of dict.txt: one word per line; each line is divided into three parts separated by a space: word, word frequency, POS tag. If file_name is a path or a file opened in binary mode, the dictionary must be UTF-8 encoded. The word frequency and POS tag can be omitted respectively. The word frequency will be filled with a suitable value if omitted. For example: 创新办 3 i云计算 5凱特琳 nz台中 Change a Tokenizer’s tmp_dir and cache_file to specify the path of the cache file, for using on a restricted file system. Example: 云计算 5李小福 2创新办 3[Before]: 李小福 / 是 / 创新 / 办 / 主任 / 也 / 是 / 云 / 计算 / 方面 / 的 / 专家 /[After]: 李小福 / 是 / 创新办 / 主任 / 也 / 是 / 云计算 / 方面 / 的 / 专家 / Modify dictionary Use add_word(word, freq=None, tag=None) and del_word(word) to modify the dictionary dynamically in programs. Use suggest_freq(segment, tune=True) to adjust the frequency of a single word so that it can (or cannot) be segmented. Note that HMM may affect the final result. Example: >>> print('/'.join(jieba.cut('如果放到post中将出错。', HMM=False)))如果/放到/post/中将/出错/。>>> jieba.suggest_freq(('中', '将'), True)494>>> print('/'.join(jieba.cut('如果放到post中将出错。', HMM=False)))如果/放到/post/中/将/出错/。>>> print('/'.join(jieba.cut('「台中」正确应该不会被切开', HMM=False)))「/台/中/」/正确/应该/不会/被/切开>>> jieba.suggest_freq('台中', True)69>>> print('/'.join(jieba.cut('「台中」正确应该不会被切开', HMM=False)))「/台中/」/正确/应该/不会/被/切开 Keyword Extraction import jieba.analyse jieba.analyse.extract_tags(sentence, topK=20, withWeight=False, allowPOS=()) sentence: the text to be extracted topK: return how many keywords with the highest TF/IDF weights. The default value is 20 withWeight: whether return TF/IDF weights with the keywords. The default value is False allowPOS: filter words with which POSs are included. Empty for no filtering. jieba.analyse.TFIDF(idf_path=None) creates a new TFIDF instance, idf_path specifies IDF file path. Example (keyword extraction) https://github.com/fxsjy/jieba/blob/master/test/extract_tags.py Developers can specify their own custom IDF corpus in jieba keyword extraction Usage: jieba.analyse.set_idf_path(file_name) file_name is the path for the custom corpus Custom Corpus Sample:https://github.com/fxsjy/jieba/blob/master/extra_dict/idf.txt.big Sample Code:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_idfpath.py Developers can specify their own custom stop words corpus in jieba keyword extraction Usage: jieba.analyse.set_stop_words(file_name) file_name is the path for the custom corpus Custom Corpus Sample:https://github.com/fxsjy/jieba/blob/master/extra_dict/stop_words.txt Sample Code:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_stop_words.py There’s also a TextRank implementation available. Use: jieba.analyse.textrank(sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v')) Note that it filters POS by default. jieba.analyse.TextRank() creates a new TextRank instance. Part of Speech Tagging jieba.posseg.POSTokenizer(tokenizer=None) creates a new customized Tokenizer. tokenizer specifies the jieba.Tokenizer to internally use. jieba.posseg.dt is the default POSTokenizer. Tags the POS of each word after segmentation, using labels compatible with ictclas. Example: >>> import jieba.posseg as pseg>>> words = pseg.cut("我爱北京天安门")>>> for w in words:... print('%s %s' % (w.word, w.flag))...我 r爱 v北京 ns天安门 ns Parallel Processing Principle: Split target text by line, assign the lines into multiple Python processes, and then merge the results, which is considerably faster. Based on the multiprocessing module of Python. Usage: jieba.enable_parallel(4) Enable parallel processing. The parameter is the number of processes. jieba.disable_parallel() Disable parallel processing. Example: https://github.com/fxsjy/jieba/blob/master/test/parallel/test_file.py Result: On a four-core 3.4GHz Linux machine, do accurate word segmentation on Complete Works of Jin Yong, and the speed reaches 1MB/s, which is 3.3 times faster than the single-process version. Note that parallel processing supports only default tokenizers, jieba.dt and jieba.posseg.dt. Tokenize: return words with position The input must be unicode Default mode result = jieba.tokenize(u'永和服装饰品有限公司')for tk in result:print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2])) word 永和 start: 0 end:2word 服装 start: 2 end:4word 饰品 start: 4 end:6word 有限公司 start: 6 end:10 Search mode result = jieba.tokenize(u'永和服装饰品有限公司',mode='search')for tk in result:print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2])) word 永和 start: 0 end:2word 服装 start: 2 end:4word 饰品 start: 4 end:6word 有限 start: 6 end:8word 公司 start: 8 end:10word 有限公司 start: 6 end:10 ChineseAnalyzer for Whoosh from jieba.analyse import ChineseAnalyzer Example: https://github.com/fxsjy/jieba/blob/master/test/test_whoosh.py Command Line Interface $> python -m jieba --helpJieba command line interface.positional arguments:filename input fileoptional arguments:-h, --help show this help message and exit-d [DELIM], --delimiter [DELIM]use DELIM instead of ' / ' for word delimiter; or aspace if it is used without DELIM-p [DELIM], --pos [DELIM]enable POS tagging; if DELIM is specified, use DELIMinstead of '_' for POS delimiter-D DICT, --dict DICT use DICT as dictionary-u USER_DICT, --user-dict USER_DICTuse USER_DICT together with the default dictionary orDICT (if specified)-a, --cut-all full pattern cutting (ignored with POS tagging)-n, --no-hmm don't use the Hidden Markov Model-q, --quiet don't print loading messages to stderr-V, --version show program's version number and exitIf no filename specified, use STDIN instead. Initialization By default, Jieba don’t build the prefix dictionary unless it’s necessary. This takes 1-3 seconds, after which it is not initialized again. If you want to initialize Jieba manually, you can call: import jiebajieba.initialize() (optional) You can also specify the dictionary (not supported before version 0.28) : jieba.set_dictionary('data/dict.txt.big') Using Other Dictionaries It is possible to use your own dictionary with Jieba, and there are also two dictionaries ready for download: A smaller dictionary for a smaller memory footprint: https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.small There is also a bigger dictionary that has better support for traditional Chinese (繁體): https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.big By default, an in-between dictionary is used, called dict.txt and included in the distribution. In either case, download the file you want, and then call jieba.set_dictionary('data/dict.txt.big') or just replace the existing dict.txt. Segmentation speed 1.5 MB / Second in Full Mode 400 KB / Second in Default Mode Test Env: Intel® Core™ i7-2600 CPU @ 3.4GHz;《围城》.txt 本篇文章为转载内容。原文链接:https://blog.csdn.net/yegeli/article/details/107246661。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-02 10:38:37
500
转载
转载文章
...情况。 然而这个基于Java的日志记录工具已经在企业记录中无处不在。例如根据软件公司Sonatype的一份报告显示,在过去的三个月里,Log4j的下载量就已经超过3000万次。 Log4j是Sonatype公司旗下的Black Duck Open Hub所研发的研究工具。Log4j有着440,000行代码,由近200名开发人员贡献了将近24,000行代码。其实与其他开源项目相比,这是一个庞大的开发团队。但是如果关注数据的话,就会发现超过70%的工作是仅仅靠五个人来完成的。 Log4j的主页上展示了十几位项目团队的成员。而大多项目的开发人员要比其原本需要的少得多----这是高度依赖开发人员团队所呈现出来的问题。 “如今几乎没有人愿意为现有的开源项目作出贡献”,来自DNS网络公司NS1的杰出工程师Jeremy Strech说,“因为通常来说,这没有直接的物质回报,也很少提供荣誉----大多数用户甚至不知道他们所用的软件是谁维护的。” 他说,开源贡献者们最常见的动机就是添加他们自己想要的功能。“一旦实现了这一点,他们几乎都不会留下来。” 与此同时,随着项目的逐渐火爆,对于维护方面的核心团队来说,他们的负担也在不断增加。 “更多的用户意味有着更多的功能需求和错误报告----但不是更多的维护人员”,Stretch说。“曾经令人愉快的爱好很快就会变成一项乏味的项目,所以很多维护人员选择干脆完全放弃他们的项目,这也是可以理解的。” Part1公地悲剧 开源软件的生态系统,就是“公地悲剧”的一个完美例子。 这个悲剧就是---当一种资源,无论是一个超限的公园还是一个开源项目,所有人都在使用而没有人贡献之时,最终都会因为过度使用和投入不足而崩溃坍塌。 这种方式可以在短期内为你节省资金,但随着时间的推移,它可能会变成项目里致命的缺陷。 拿Linux来说,这个开源操作系统在全球前100万台服务器中运行率在96%以上,且这些服务器90%的云基础设施也都在Linux上。更不用说世界上85%的智能手机都运行着Linux,即Android操作系统。 这些常见开源项目的列表还在逐渐增加着。 所以没有开源,今天的大部分技术基础设施的建设也将会戛然而止。 “这是一个很现实的问题”,Data.org的执行董事Danil Mikhailov说,该组织是由万事达包容性发展中心和洛克菲勒基金会支持,旨在促进使用数据科学来应对当今社会所面临的巨大挑战的非营利性组织。 虽然几乎所有组织都在使用着开源软件,但只有少数组织为这些项目作出了贡献。The New Stack、Linux Foundation Research 和 TODO Group 在 9 月发布的一项调查中,42% 的参与者表示,他们至少有时会为开源项目做出贡献。 而同一项研究表明,只有36%的组织会培训他们的工程师为开源作出贡献。 个体公司应该支持贡献这些他们使用最多且对他们成功至关重要的项目,Mikhailov认为:“如果你使用开源,你就应该为他做出属于你自己的贡献。” Part2OSPO的好处:更少的技术负债,更好的招聘效果 参与开源社区----特别是在内部开源计划办公室(OSPO)的指导下----不仅可以保证对组织成功至关重要项目的健康发展,还可以提高项目安全性,同时可以允许工程师在项目发展规划中起到更大的作用。 例如,如果一家公司使用了开源工具,并对其进行了一些调整使其变得更好。但如果这项改进没有反馈到开源社区,那么开源项目的正式版本就会一开始与该公司所使用的版本有所不同。 “当原始数据来源发生变化且你所使用的是不同的版本时,你的技术负债将越来越多。而这些差异是以天为单位迅速增长的。”VMware 开源营销和战略总监 Suzanne Ambiel 表示,“所以你很快就会变成一个开源项目里独一无二变体的‘自豪’用户和维护人员。” “如果技术负债越来越多,那么公司的管理成本则会非常昂贵”。 实际上对于开源活动的支持也变成了一种招聘途径。“这真是一块吸引人才的磁铁,”Ambiel说,“这也是新员工所寻求的“。 她还提到,一些工程经理可能会对贡献开源而减损核心产品的开发的精力而感到担忧。她补充到,他们的理由有可能是这样的:“我只有有限的才华与时间,且我需要这些只做我认为可以处理且看到投资回报的事情。” 但她说,这是一种鼠目寸光的态度。支持开源社区并且作出贡献的员工,可以从中培养技能与增长才干。 云安全供应商 Sysdig 的首席技术官兼创始人 Loris Degionni 也赞同这一观点:“找到为开源做出贡献的员工无疑就找到一座金矿,”他说。 他认为,这些参与开源的员工更具备公司想拥有的竞争力并将一些功能融入至社区所支持的标准中。且在人才争夺战中,拥抱开源的公司也更受到开发人员的青睐。 “最后,开源项目是由你可能无法聘请的技术专家社区推动的”,他说,“当员工积极参与并于这些专家合作时,他们将能更好地深入这些顶级的实践,并将这些收获带回到你的组织之中。” “当原始数据来源发生变化且你所使用的是不同的版本时,你的技术负债将越来越多...所以你很快就会变成一个开源项目里独一无二变体的”自豪“用户和维护人员。”— Suzanne Ambiel,VMware 开源营销和战略总监 “但是这一切终究不会白费--开发人员不应该把空闲时间用在磨练他们的技能上,因为你的公司很快就会在他们的努力中看到好处。” Degionni认为,OSPO(开源计划办公室)可以帮助公司实现这些目标,以及帮助确定贡献的优先级并确保合作的进行。除此之外,他们也可以对公司内部开发应用程序方面的治理提供相关帮助。 “开源团队的成员也可以成为开源技术的伟大内部传播者,并充当组织与更广泛社区之间的桥梁。”他补充道。 在 The New Stack、Linux Foundation Research 和 TODO Group 的 9 月调查中,近 53% 的拥有 OSPO的组织表示,由于拥有了OSPO,他们看到了更多创新,而近 43% 的组织表示,他们在外部开源项目的参与度上有所增加。 Part3更多OSPO的好处:商业优势 网络安全公司 ThreatX 的首席创新官 Tom Hickman 表示,为开源社区做出贡献,不仅有助于社区,还有助于为社区做出贡献的公司。 “围绕一个项目而发展的开发人员社区,有助于代码库的形成,并吸引更多的开发人员参与”,他说,“这可以变成一个良性循环。” 此外,根据哈佛商学院的研究,为开源项目作出贡献的公司从使用开源的项目中获得的生产价值,是不参与开源项目公司的两倍。 Cloud Native Computing Foundation 的首席技术官 Chris Aniszczyk 说,世界上许多巨头公司都为开源作出了贡献。他还提到,开源贡献者的指数是作为公司是否有所作为的参考。 科技巨头占据了这份榜单的主导地位:谷歌、微软、红帽、英特尔、IBM、亚马逊、Facebook、VMware、GitHub 和 SAP 依次是排名前 10 的贡献者。但Aniszczyk 表示,但也有很多终端用户公司进入前 100 名,包括 Uber、BBC、Orange、Netflix 和 Square。 “我们一直知道,在上游项目中工作不仅仅是关正确与否----它是开源软件开发的最佳方法,也是向客户提供开源福利的最佳方式”他说,“很高兴看到IT领导者们也认识到了这一点。” 为了和这些公司一起作出贡献,公司也需要有自己的开源策略,而拥有一个开源计划办公室则可以为其提供帮助。 “在使用开源软件方面,OPSO为公司提供了一个至关重要的能力中心”他说。 这与公司拥有安全运营中心的方式类似,他说。 “围绕一个项目而发展的开发人员社区,有助于代码库的形成,并吸引更多的开发人员参与,这可以变成一个良性循环。” ——Tom Hickman,ThreatX 首席创新官 “如果你对安全团队进行相应投资,你通常是不会期望你的软件是安全的,也无法及时应对安全事件。”他说。 “同样的逻辑也适用于 OSPO,这就是为什么你会看到许多领先的公司,例如Apple、Meta、Twitter、Goldman Sachs、Bloomberg 和 Google 都拥有 OSPO。他们走在了趋势的前面。” 而对组织内的开源活动的支持态度亦可成为软件供应商们的差异化原因与营销的机会。 根据Red Hat 2月分发布的一项调查,82%的IT领导者更倾向于选择为开源社区作出贡献的软件供应商。 受访者表示,当供应商支持开源社区时,就表示着他们更熟悉开源的流程并且在客户遇到技术难题时会更加有效。 但收益的不仅仅是软件供应商们。 根据 The New Stack、Linux Foundation Research 和 TODO Group 9 月份的调查,57% 拥有 OSPO 的组织将使用它们来进一步发展战略关系和建立合作伙伴关系。 十年前,Mark Hinkle 在 Citrix 工作时创办了一个开源计划办公室。他指出了在内部拥有一个 OSPO将如何使公司受益。 “对于我们来说,最大的工作是让不熟悉开源的员工学会并参与其中,成为优秀的社区成员”,他说,“我们还就如何确保我们的IP不会在没有正确理解的情况下进入项目的情况提供了指导,并确保我们没有与我们企业软件许可相冲突的开源项目合作。” 他说,OSPO还帮助Citrix确定了公司参与开源项目和Linux基金会等贸易组织的战略机会。 如今,他是云原生开源集成平台 TriggerMesh 的首席执行官兼联合创始人。 他说,参与开源系统对公司来说有着重大的经济效益。 “我们参与Knative是为了分享我们基础底层平台的开发,但作为业务的一部分,我们也拥有相关的增值服务。”他说,“通过共享该平台的研发,这为我们提供了更多的资源来改进我们自己的差异化技术。” Part4如何入门开源 在 The New Stack、Linux Foundation Research 和 TODO Group 的 9 月份调查中,有 63% 的公司表示,拥有OSPO 对其工程或产品团队的成功至关重要,高于上一年度该项研究数据的 54%。 其中77% 的人表示他们的开源程序对他们的软件实践产生了积极影响,例如提高了代码质量。 但公司也不可能总是为他们使用的每一个开源项目而花费精力。 “首先,节流一下”,VMware 的 Ambiel 建议道。 公司应该关注投入使用中最有意义的项目。而这也是OSPO可以帮助确定优先事项并确保技术与战略一致性的领域。 之后,开发人员应该自己去了解一下。项目通常提供相关在线文档,一般包含贡献着指南、治理文档和未解决问题列表。 “对于那些你较感兴趣的项目中,你可以介绍一下自己----打个招呼”,她说。“然后转到Slack频道或者分发列表,询问他们需要帮助的地方。也许他们不需要帮助,一切完好;又或者他们也有可能使用新人来审查核验代码。” Ambiel 说,开源计划办公室不仅可以帮助制定为开源社区做出贡献的商业案例,还可以帮助公司以安全、可靠和健全的方式来做这件事。 “如果我为一家公司工作,并想为开源做出贡献,我不想意外披露、泄露或破坏任何专利,”她说。“而OSPO可以帮助您做出明智的选择。” 她说,OSPO还可以在开源方面提供领导力和指导理念的支持。“它可以提供引领、指导、辅导和最佳实践的作用。” Aqua Security的开发人员倡导者Anaïs Urlichs则认为,支持开源的承诺必须从高层开始。 她说,“公司在多数时候往往不重视对开源的投资,所以员工自然而然不被鼓励对此作出贡献。” 在这些情况下,员工对于开源的热情也会在空闲时间里对开源的建设而消散殆尽,这对于开源的发展来说是不可持续的。 “如果公司对开源项目依赖度高,那么将开源贡献纳入工程师的日程安排是很重要的,”她说。“一些公司定义了员工可以为开源建设的时间百分比,将其作为他们正常工作日的一部分。” The New Stack 是 Insight Partners 的全资子公司,Insight Partners 是本文提到的以下公司的投资者:Sysdig、Aqua Security。 中英对照版 How an OSPO Can Help Your Engineers Give Back to Open Source OSPO (开源项目办公室)是如何使工程师回馈开源的 When it comes to open source software, there’s a big and growing problem: most organizations are takers, not givers. 谈到开源软件,有一个较大且日益严重的问题:大多数组织都是索取者,而不是给予者。 There’s a classic XKCD comic that shows a giant structure representing modern digital infrastructure, dependent on a tiny component created by “some random person in Nebraska” who has been “thanklessly maintaining since 2003.” 经典漫画XKCD展示了一个代表现代数字基础设施的巨大结构,它依赖于“内布拉斯加州的某位人士”创建的微小组件,该组件“自2003年来一直都处于吃力不讨好的状态”。 Randall Monroe’s XKCD comic illustrates the open source dilemma: overreliance on a small number of volunteer project maintainers. Randall Monroe 的XKCD漫画展示了目前开源面临的窘境:过度依赖少数项目维护志愿者的志愿服务。 This would have been funny, except that this is exactly what happened when security vulnerabilities were discovered in Log4j last December. (开源项目由志愿者自发来维护,)这听起来像是一件很滑稽的事情,但事实上去年十二月在Log4j中发现的安全漏洞也确实存在着上述情况。 The Java-based logging tool is ubiquitous in enterprise publications. In the last three months, for example, Log4j has been downloaded more than 30 million times, according to a report by the enterprise software company Sonatype. 然而这个基于Java的日志记录工具已经在企业内部刊物中无处不在。例如根据软件公司Sonatype的一份报告显示,在过去的三个月里,Log4j的下载量就已经超过3000万次。 The tool has 440,000 lines of code, according to Synopsys‘ Black Duck Open Hub research tool, with nearly 24,000 contributions by nearly 200 developers. That’s a large dev team compared to other open source projects. But looking closer at the numbers, more than 70% of commits were by just five people. 根据Synopsys(新思)公司旗下的Black Duck Open Hub 研究工具显示。Log4j有着440,000行代码,由近200名开发人员贡献了将近24,000行代码。其实与其他开源项目相比,这是一个庞大的开发团队。但是如果关注数据的话,就会发现超过70%的提交是仅仅靠五个人来完成的。 Log4j’s home page lists about a dozen members on its project team. Most projects have far fewer developers working on them — and that presents a problem for the organizations that depend on them. Log4j的主页上展示了十几位项目团队的成员。而大多项目的开发人员要比其原本需要的少得多----这是高度依赖开发人员团队所呈现出来的问题。 “There is little incentive for anyone today to contribute to an existing open source project,” said Jeremy Stretch, distinguished engineer at NS1, a DNS network company. “There’s usually no direct compensation, and few accolades are offered — most users don’t even know who maintains the software that they use.” “如今的人没有什么动力去为现有的开源项目做贡献”,来自DNS网络公司NS1的杰出工程师Jeremy Strech说,“因为通常来说,这没有直接的物质回报,也很少提供荣誉----大多数用户甚至不知道他们所用的软件是谁维护的。” The most common motivation among open source contributors is to add a feature that they themselves want to see, he said. “Once this has been achieved, the contributor rarely sticks around.” 他说,开源贡献者们最常见的动机就是添加他们自己想要的功能。“一旦实现了这一点,他们几乎都不会留下来。” Meanwhile, as a project becomes more popular, the burden on the core team of maintainers keeps increasing. 与此同时,随着项目的逐渐流行,对于维护方面的核心团队来说,他们的负担也在不断增加。 “More users means more feature requests and more bug reports — but not more maintainers,” Stretch said. “What was once an enjoyable hobby can quickly become a tedious chore, and many maintainers understandably opt to simply abandon their projects altogether.” “更多的用户意味有着更多的功能需求和错误报告----但不是更多的维护人员”,Stretch说。“曾经令人愉快的爱好很快就会变成一项乏味的项目,所以很多维护人员选择干脆完全放弃他们的项目,这也是可以理解的。” Part1The Tragedy of the Commons The open source software ecosystem is a perfect example of the “tragedy of the commons.” 开源软件的生态系统,就是“公地悲剧”的一个完美例子。 And the tragedy is — when everyone uses, but no one contributes, that resource — whether it’s an overrun park or an open source project — eventually collapses from overuse and underinvestment. Everyone loves using free stuff, but everyone expects someone else to take care of it. 这个悲剧就是---当一种资源,无论是一个超限的公园还是一个开源项目,所有人都在使用而没有人贡献之时,最终都会因为过度使用和投入不足而崩溃坍塌。 This approach can save you money in the short term, but it can become a fatal flaw over time. Especially since open source software is everywhere, running everything. 这种方式可以在短期内为你节省资金,但随着时间的推移,它可能会变成项目里致命的缺陷。 Linux, for example, the open source operating system, runs on 96% of the world’s top 1 million servers, and 90% of all cloud infrastructure is on Linux. Not to mention that 85% of all smartphones in the world run Linux, in the form of the Android OS. 拿Linux来说,这个开源操作系统在全球前100万台服务器中运行率在96%以上,且这些服务器90%的云基础设施也都在Linux上。更不用说世界上85%的智能手机都运行着Linux,即Android操作系统。 Then there’s Java, Apache, WordPress, Cassandra, Hadoop, MySQL, PHP, ElasticSearch, Kubernetes — the list of ubiquitous open source projects goes on and on. 还有Java, Apache, WordPress, Cassandra, Hadoop, MySQL, PHP, ElasticSearch, Kubernetes--这些常见开源项目的列表还在逐渐增加着。 Without open source, much of today’s technical infrastructure would immediately grind to a halt. 如果没有开源,今天的大部分技术基础设施的建设也将会戛然而止。 “It is a real problem,” said Danil Mikhailov, executive director at Data.org, a nonprofit backed by the Mastercard Center for Inclusive Growth and The Rockefeller Foundation that promotes the use of data science to tackle society’s greatest challenges. “这是一个很现实的问题”,Data.org的执行董事Danil Mikhailov说,该组织是由万事达包容性发展中心和洛克菲勒基金会支持,旨在促进使用数据科学来应对当今社会所面临的巨大挑战的非营利性组织。 While nearly all organizations use open source software, only a minority contribute to those projects. Forty-two percent of participants in a survey released in September by The New Stack, Linux Foundation Research, and the TODO Group said tthey contribute at least sometimes to open source projects. 虽然几乎所有组织都在使用着开源软件,但只有少数组织为这些项目作出了贡献。The New Stack、Linux Foundation Research 和 TODO Group 在 9 月发布的一项调查中,42% 的参与者表示,他们至少有时会为开源项目做出贡献。 The same study showed that only 36% of organizations train their engineers to contribute to open source. 而同一项研究表明,只有36%的组织会培训他们的工程师为开源作出贡献。 Individual companies should support projects that they use the most and are critical to their success, Mikhailov said: “If you use, you contribute.” 个体公司应该支持贡献这些他们使用最多且对他们成功至关重要的项目,Mikhailov认为:“如果你使用开源,你就应该为他做出属于你自己的贡献。” Part2OSPO Benefits:Less Tech Debt,Better Recruiting Participating in open source communities — especially when guided by an in-house open source program office (OSPO) — can help ensure the health of projects critical to your organization’s success, improve those projects’ security, and allow your engineers to have more impact in the projects’ development road map. 参与开源社区——特别是在内部开源项目办公室(OSPO)的指导下——不仅可以保证对组织成功至关重要项目的健康发展,还可以提高项目安全性,同时可以允许工程师在项目发展规划中起到更大的影响。 Say, for example, a company uses an open source tool and modifies it a little to make it better. If that improvement isn’t contributed back to the community, then the official version of the open source project will start to diverge from what the company is using 例如,如果一家公司使用了开源工具,并对其进行了一些调整使其变得更好。但如果这项改进没有反馈到开源社区,那么开源项目的正式版本就会一开始与该公司所使用的版本有所不同。 “You start to grow technical debt because when the original source changes and you’ve got a different version. Those differences grow rapidly, compounding daily. It doesn’t take long for you to be the proud user and maintainer of a one-of-a-kind open source project variant,” said Suzanne Ambiel, director, open source marketing and strategy at VMware. “当原始代码来源发生变化且你所使用的是不同的版本时,你的技术负债将越来越多。而这些差异是以天为单位迅速增长的。”VMware 开源营销和战略总监 Suzanne Ambiel 表示,“所以你很快就会变成一个开源项目里独一无二变体的‘自豪’用户和维护人员。” “The technical debt gets bigger and bigger and it gets very expensive for a company to manage.” “如果技术负债越来越多,那么公司的管理成本则会非常昂贵”。 Support for open source activity can also be a recruiting tool. “It’s really a talent magnet,” said Ambiel. “It’s one of the things that new hires look for.” 实际上对于开源活动的支持也变成了一种招聘途径。“这真是一块吸引人才的磁铁,”Ambiel说,“这也是新员工所寻求的“。 Some engineering managers might worry that open source contributions will detract from core product development, she said. Their rationale, she added, might run along the lines of, “I only have so much talent, and so many hours, and I need them to only work on things where I can measure and see the return on investment.” 她还提到,一些工程经理可能会对贡献开源而减损核心产品的开发的精力而感到担忧。她补充到,他们的理由有可能是这样的:“我只有有限的才华与时间,且我需要这些只做我认为可以度量且看到投资回报的事情。” But that attitude, she said, is shortsighted. Supporting employees who contribute to open source communities can build skills and develop talent, she said. 但她说,这是一种鼠目寸光的态度。支持开源社区并且作出贡献的员工,可以从中培养技能与增长才华。 Loris Degionni, chief technology officer and founder at Sysdig, a cloud security vendor, echoed this notion: “Finding employees who contribute to open source is a gold mine,” said. 云安全供应商 Sysdig 的首席技术官兼创始人 Loris Degionni 也赞同这一观点:“找出为开源做出贡献的员工无疑就找到一座金矿,”他说。 These employees are more capable of delivering features a company wants to use and merge them into community-supported standards, he said. And in a war for talent, companies that embrace open source are more attractive to developers. 他认为,这些参与开源的员工更具备公司想拥有的竞争力并将一些功能融入至社区所支持的标准中。且在人才争夺战中,拥抱开源的公司也更受到开发人员的青睐。 “Lastly, open source is driven by a community of technical experts you may not be able to hire,” he said. “When employees actively contribute and collaborate with these experts, they’ll be better informed of best practices and bring them back to your organization. “最后,开源项目是由你可能无法聘请的技术专家社区推动的”,他说,“当员工积极参与并于这些专家合作时,他们将能更好地深入这些最佳实践,并将这些收获带回到你的组织之中。” “You start to grow technical debt because when the original source changes and you’ve got a different version … It doesn’t take long for you to be the proud user and maintainer of a one-of-a-kind open source project variant.” —Suzanne Ambiel, director, open source marketing and strategy, VMware “当原始数据来源发生变化且你所使用的是不同的版本时,你的技术负债将越来越多...所以你很快就会变成一个开源项目里独一无二变体的”自豪“用户和维护人员。” — Suzanne Ambiel,VMware 开源营销和战略总监 “All of this should be rewarded — developers shouldn’t have to spend their free time honing their skills, as your company will quickly see benefits from their efforts.” “但是这一切终究不会白费--开发人员不应该把业余时间用在磨练他们的技能上,因为你的公司很快就会在他们的努力中看到好处。” An OSPO, Degionni suggested, can help achieve these goals, as well as help prioritize contributions and ensure collaboration. In addition, they can help provide governance that mirrors what companies would have for internally developed applications. Degionni认为,OSPO(开源计划办公室)可以帮助公司实现这些目标,以及帮助确定贡献的优先级并确保合作的进行。除此之外,他们也可以对公司内部开发应用程序方面的治理提供相关帮助。 “Members of the open source team are also in a position to be great internal evangelists for open source technologies, and act as bridges between the organization and the broader community,” he added. “开源团队的成员也可以成为开源技术的伟大内部布道师,并充当组织与更广泛社区之间的桥梁。”他补充道。 In the September survey from The New Stack, Linux Foundation Research and the TODO Group, nearly 53% of organizations with OSPOs said they saw more innovation as a result of having an OSPO, while almost 43% said they saw increased participation in external open source projects. 在 The New Stack、Linux Foundation Research 和 TODO Group 的 9 月调查中,近 53% 的拥有 OSPO的组织表示,由于拥有了OSPO,他们看到了更多创新,而近 43% 的组织表示,他们在外部开源项目的参与度上有所增加。 Part3More OSPO Benefits:A Business Edge Contributing to open source communities doesn’t just help the communities, but the companies that contribute to them, said Tom Hickman, chief innovation officer at ThreatX, a cybersecurity firm. 网络安全公司 ThreatX 的首席创新官 Tom Hickman 表示,为开源社区做出贡献,不仅有助于社区,还有助于为社区做出贡献的公司。 “Growing the community of developers around a project helps the code base, and attracts more developers,” he said. “It can become a virtuous circle.” “围绕一个项目而发展的开发人员社区,有助于代码库的形成,并吸引更多的开发人员参与”,他说,“这可以变成一个良性循环。” Also, companies that contribute to open source projects get twice the productive value from their use of open source than companies that don’t, according to research by Harvard Business School. 此外,根据哈佛商学院的研究,为开源项目作出贡献的公司从使用开源的项目中获得的生产价值,是不参与开源项目公司的两倍。 Many of the biggest companies in the world are contributing to open source, said Chris Aniszczyk, chief technology officer at Cloud Native Computing Foundation. He pointed to the Open Source Contributor Index as a reference for exactly just how much companies are doing. Cloud Native Computing Foundation 的首席技术官 Chris Aniszczyk 说,世界上许多巨头公司都为开源作出了贡献。他还提到,开源贡献者的指数是作为公司是否有所作为的参考。 The tech giants dominate the list: Google, Microsoft, Red Hat, Intel, IBM, Amazon, Facebook, VMware, GitHub and SAP are the top 10 contributors, in that order. But there are also a lot of end users on the top 100 list, said Aniszczyk, including Uber, the BBC, Orange, Netflix, and Square. 科技巨头占据了这份榜单的主导地位:谷歌、微软、红帽、英特尔、IBM、亚马逊、Facebook、VMware、GitHub 和 SAP 依次是排名前 10 的贡献者。但Aniszczyk 表示,但也有很多终端用户公司进入前 100 名,包括 Uber、BBC、Orange、Netflix 和 Square。 “We’ve always known working in upstream projects is not just the right thing to do —it’s the best approach to open source software development and the best way to deliver open source benefits to our customers,” he said. “It’s great to see that IT leaders recognize this as well.” “我们一直知道,在上游项目中工作不仅仅是关正确与否----它是开源软件开发的最佳方法,也是向客户提供开源福利的最佳方式“他说,“很高兴看到IT领导者们也认识到了这一点。” To contribute alongside these giants, companies need to have their own open source strategies, and having an open source program office can help. 为了和这些公司一起作出贡献,公司也需要有自己的开源策略,而拥有一个开源项目办公室则可以为其提供帮助。 “OSPOs provide a critical center of competency in a company when it comes to utilizing open source software,” he said. “在使用开源软件方面,OPSO为公司提供了一个至关重要的能力中心”他说。 It’s similar to the way that companies have security operations centers, he said. 这与公司拥有安全运营中心的方式类似,他说。 “Growing the community of developers around a project helps the code base, and attracts more developers. It can become a virtuous circle.” —Tom Hickman, chief innovation officer, ThreatX “围绕一个项目而发展的开发人员社区,有助于代码库的形成,并吸引更多的开发人员参与,这可以变成一个良性循环。” ——Tom Hickman,ThreatX 首席创新官 “If you don’t make the investment in a security team, you generally don’t expect your software to be secure or be able to respond to security incidents in a timely fashion,” he said. “如果你没有对安全团队进行相应投资,你通常是不会期望你的软件是安全的,也无法及时响应安全事件。”他说。 “The same logic applies to OSPOs and is why you see many leading companies out there such as Apple, Meta, Twitter, Goldman Sachs, Bloomberg, and Google all have OSPOs. They are ahead of the curve.” “同样的逻辑也适用于 OSPO,这就是为什么你会看到许多领先的公司,例如 Apple、Meta、Twitter、Goldman Sachs、Bloomberg 和 Google 都拥有 OSPO。他们走在了趋势的前面。” Support for open source activity within your organization can become a differentiator and marketing opportunity for software vendors. 而对组织内的开源活动的支持态度亦可成为软件供应商们的差异化原因与营销的机会。 According to a Red Hat survey released in February, 82% of IT leaders are more likely to select a vendor who contributes to the open source community. 根据Red Hat2月分发布的一项调查,82%的IT领导者更倾向于选择为开源社区作出贡献的软件供应商。 Respondents said that when vendors support open source communities they are more familiar with open source processes and are more effective if customers have technical challenges. 受访者表示,当供应商支持开源社区时,就表示着他们更熟悉开源的流程并且在客户遇到技术难题时会更加有效。 But it’s not just software vendors who benefit. 但收益的不仅仅是软件供应商们。 According to September’s survey by The New Stack, Linux Foundation Research, and the TODO Group, 57% of organizations with OSPOs use them to further strategic relationships and build partnerships. 根据 The New Stack、Linux Foundation Research 和 TODO Group 9 月份的调查,57% 拥有 OSPO 的组织将使用它们来进一步发展战略关系和建立合作伙伴关系。 Mark Hinkle started an open source program office back when he worked at Citrix a decade ago. He pointed out how having an OSPO in-house benefited the company. 十年前,Mark Hinkle 在 Citrix 工作时创办了一个开源计划办公室。他指出了在内部拥有一个 OSPO将如何使公司受益。 “For us the biggest job was to educate our employees who weren’t familiar with open source to get involved and be good community members,” he said. “We also provided guidance on how to make sure our IP didn’t enter projects without proper understanding and we made sure we didn’t incorporate open source that conflicted with our enterprise software licensing.” “对于我们来说,最大的工作是让不熟悉开源的员工学会并参与其中,成为优秀的社区成员”,他说,“我们还就如何确保我们的IP不会在没有正确理解的情况下进入项目的情况提供了指导,并确保我们没有与我们企业软件许可相冲突的开源项目合作。” The OSPO also helped Citrix identify strategic opportunities for the company to participate in open source projects and trade organizations like The Linux Foundation, he said. 他说,OSPO还帮助Citrix确定了公司参与开源项目和Linux基金会等贸易组织的战略机会。 Today, he’s the CEO and co-founder of TriggerMesh, a cloud native, open source integration platform. 如今,他是云原生开源集成平台 TriggerMesh 的首席执行官兼联合创始人。 There are some significant economic benefits to participating in the open source ecosystem, he said. 他说,参与开源系统对公司来说有着重大的经济效益。 “We participate in Knative to share the development of our underlying platform but we develop value-added services as part of our business,” he said. “By sharing the R and D for the platform, it gives us more resources to develop our own differentiated technology.” “我们参与Knative是为了分享我们基础底层平台的开发,但作为业务的一部分,我们也拥有相关的增值服务。”他说,“通过共享该平台的研发,这为我们提供了更多的资源来改进我们自己的差异化技术。” Part4How to Get Started in Open Source Sixty-three percent of companies in the September survey from The New Stack, Linux Foundation Research and the TODO Group said that having an OSPO was very or extremely critical to the success of their engineering or product teams, up from 54% in the previous annual study. 在 The New Stack、Linux Foundation Research 和 TODO Group 的 9 月份调查中,有 63% 的公司表示,拥有OSPO 对其工程或产品团队的成功至关重要,高于上一年度该项研究数据的 54%。 In particular, 77% said that their open source program had a positive impact on their software practices, such as improved code quality. 其中77% 的人表示他们的开源程序对他们的软件实践产生了积极影响,例如提高了代码质量。 But companies can’t always contribute to every single open source project that they use. 但公司也不可能总是为他们使用的每一个开源项目而花费精力。 “First, thin the herd a little bit,” advised VMware’s Ambiel. “首先,节流一下”,VMware 的 Ambiel 建议道。 Companies should look at the projects that make the most sense for their use cases. This is an area where an OSPO can help set priorities and ensure technical and strategic alignment. 公司应该关注投入使用中最有意义的项目。而这也是OSPO可以帮助确定优先事项并确保技术与战略一致性的领域。 Then, developers should go and check out the projects themselves. Projects typically offer online documentation, often with contributor guides, governance documents, and lists of open issues. 之后,开发人员应该自己去了解一下。项目通常提供相关在线文档,一般包含贡献着指南、治理文档和未解决问题列表。 “For the projects that rise to the top of your strategic list, introduce yourself — say hello,” she said. “Go to the Slack channel or the distribution list and ask where they need help. Maybe they don’t need help and everything is good. Or maybe they can use a new person to review code.” “对于那些上升到你的战略清单顶端的项目,你可以介绍一下自己----打个招呼”,她说。“然后转到Slack频道或者分发列表,询问他们需要帮助的地方。也许他们不需要帮助,一切完好;又或者他们也有可能使用新人来审查核验代码。” An open source program office can not only help make a business case for contributing to the open source community, Ambiel said, but can help companies do it in a way that’s safe, secure and sound. Ambiel 说,开源项目办公室不仅可以帮助制定为开源社区做出贡献的商业案例,还可以帮助公司以安全、可靠和健全的方式来做这件事。 “If I work for a company and want to contribute to open source, I don’t want to accidentally disclose, divulge or undermine any patents,” she said. “An OSPO helps you make smart choices.” “如果我为一家公司工作,并想为开源做出贡献,我不想意外披露、泄露或破坏任何专利,”她说。“而OSPO可以帮助您做出明智的选择。” An OSPO can also help provide leadership and the guiding philosophy about supporting open source, she said. “It can provide guidance, mentorship, coaching and best practices.” 她说,OSPO还可以在开源方面提供领导力和指导理念的支持。“它可以提供引领、指导、辅导和最佳实践的作用。” Commitment to support open source has to start at the top, said Anaïs Urlichs, developer advocate at Aqua Security. Aqua Security的开发人员倡导者Anaïs Urlichs则认为,支持开源的承诺必须从高层开始。 “Too often,” she said, “companies do not value investment into open source, so employees are not encouraged to contribute to it.” 她说,“公司在多数时候往往不重视对开源的投资,所以员工自然而然不被鼓励对此作出贡献。” In those cases, employees with a passion for open source end up contributing during their free time, which is not sustainable. 在这些情况下,员工对于开源的热情也会在空闲时间里对开源的建设而消散殆尽,这对于开源的发展来说是不可持续的。 “If companies rely on open source projects, it is important to make open source contributions part of an engineer’s work schedule,” she said. “Some companies define a time percentage that employees can contribute to open source as part of their normal workday.” “如果公司对开源项目依赖度高,那么将开源贡献纳入工程师的日程安排是很重要的,”她说。“一些公司定义了员工可以为开源建设的时间百分比,将其作为他们正常工作日的一部分。” The New Stack is a wholly owned subsidiary of Insight Partners, an investor in the following companies mentioned in this article: Sysdig, Aqua Security. The New Stack 是 Insight Partners 的全资子公司,Insight Partners 是本文提到的以下公司的投资者:Sysdig、Aqua Security。 相关阅读 | Related Reading 《开源合规指南(企业篇)》正式发布,为推动我国开源合规建设提供参考 “目标->用户->指标”——企业开源运营之道|瞰道@谭中意 开源之夏邀请函——仅限高校学子开启 开源社简介 开源社成立于 2014 年,是由志愿贡献于开源事业的个人成员,依 “贡献、共识、共治” 原则所组成,始终维持厂商中立、公益、非营利的特点,是最早以 “开源治理、国际接轨、社区发展、开源项目” 为使命的开源社区联合体。开源社积极与支持开源的社区、企业以及政府相关单位紧密合作,以 “立足中国、贡献全球” 为愿景,旨在共创健康可持续发展的开源生态,推动中国开源社区成为全球开源体系的积极参与及贡献者。 2017 年,开源社转型为完全由个人成员组成,参照 ASF 等国际顶级开源基金会的治理模式运作。近八年来,链接了数万名开源人,集聚了上千名社区成员及志愿者、海内外数百位讲师,合作了近百家赞助、媒体、社区伙伴。 本篇文章为转载内容。原文链接:https://blog.csdn.net/kaiyuanshe/article/details/124976824。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-05-03 09:19:23
273
转载
转载文章
...rRegistry.java:47)at org.apache.ibatis.session.Configuration.getMapper(Configuration.java:779)at org.apache.ibatis.session.defaults.DefaultSqlSession.getMapper(DefaultSqlSession.java:291)at com.itcase.dao.UserDaoTest.test1(UserDaoTest.java:18)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:498)at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)at org.junit.runners.ParentRunner.run(ParentRunner.java:309)at org.junit.runner.JUnitCore.run(JUnitCore.java:160)at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) 一般这总情况就是 > Mybatis的config文件忘记在<configuration></configuration>> 里加上以下代码了,下边的UserMapper.xml换成你们报错的文件 <mappers><mapper resource="com/itcase/dao/UserMapper.xml"/></mappers> 要是加了mapper依然报错,如果是以下错误的话:点我看另一篇博客 Caused by: org.apache.ibatis.exceptions.PersistenceException: Error building SqlSession. The error may exist in com/itcase/dao/UserMapper.xml Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/itcase/dao/UserMapper.xmlat org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80)at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64)at com.itcase.util.MybatisUtil.<clinit>(MybatisUtil.java:20)... 23 moreCaused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/itcase/dao/UserMapper.xmlat org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:121)at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:98)at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:78)... 25 moreCaused by: java.io.IOException: Could not find resource com/itcase/dao/UserMapper.xmlat org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:114)at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:100)at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:372)at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:119)... 27 more 本篇文章为转载内容。原文链接:https://blog.csdn.net/kaikai_gege/article/details/109730197。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-06-08 12:10:23
128
转载
Dubbo
...。比如说,如果你没把JAVA_HOME环境变量设置对,Dubbo就找不到Java的藏身之处(也就是安装路径),这样一来,它就没法正常启动运行啦。 解决这个问题的方法非常简单,只需要在系统环境变量中添加JAVA_HOME即可。例如,在Windows系统中,可以在"我的电脑" -> "属性" -> "高级系统设置" -> "环境变量"中添加。 三、日志配置错误 日志配置错误也是导致Dubbo无法正常运行的一个重要原因。要是你日志的配置文件,比如说logback.xml,搞错了设定,那就等于给日志输出挖了个坑。这样一来,日志就无法顺畅地“说话”了,我们也就没法通过这些日志来摸清系统的运行状况,了解它到底是怎么干活儿的了。 解决这个问题的方法也很简单,只需要检查日志配置文件中的配置是否正确即可。比如,我们可以瞅瞅日志输出的目的地是不是设定对了,还有日志的详细程度级别是否也调得恰到好处,这些小细节都值得我们关注检查一下。 四、代码示例 为了更直观地理解环境配置问题和日志配置错误,下面给出一些代码示例。 首先,来看一下不正确的环境变量设置。假设我们在没有设置JAVA_HOME的情况下尝试启动Dubbo,那么就会出现以下错误: Exception in thread "main" java.lang.UnsatisfiedLinkError: no javassist in java.library.path at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867) at java.lang.Runtime.loadLibrary0(Runtime.java:870) at java.lang.System.loadLibrary(System.java:1122) at com.alibaba.dubbo.common.logger.LoggerFactory.getLogger(LoggerFactory.java:39) at com.alibaba.dubbo.common.logger.LoggerFactory.getLogger(LoggerFactory.java:51) at com.alibaba.dubbo.config.ApplicationConfig.(ApplicationConfig.java:114) at com.example.demo.DemoApplication.main(DemoApplication.java:12) Caused by: java.lang.ClassNotFoundException: javassist at java.net.URLClassLoader.findClass(URLClassLoader.java:382) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 6 more 可以看出,由于JAVA_HOME环境变量未设置,所以无法找到Java的安装路径,从而导致了这个错误。 接下来,来看一下不正确的日志配置。假设我们在日志配置文件中错误地指定了日志输出的目标位置,那么就会出现以下错误: 2022-03-08 15:29:54,742 ERROR [main] org.apache.log4j.ConsoleAppender - Error initializing ConsoleAppender appenders named [STDOUT] org.apache.log4j.AppenderSkeleton$InvalidAppenderException: No such appender 'STDOUT' in category [com.example.demo]. at org.apache.log4j.Category.forcedLog(Category.java:393) at org.apache.log4j.Category.access$100(Category.java:67) at org.apache.log4j.Category$AppenderAttachedObject.append(Category.java:839) at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:248) at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:51) at org.apache.log4j.Category.callAppenders(Category.java:206) at org.apache.log4j.Category.debug(Category.java:267) at org.apache.log4j.Category.info(Category.java:294) at org.apache.log4j.Logger.info(Logger.java:465) at com.example.demo.DemoApplication.main(DemoApplication.java:16) 可以看出,由于日志配置文件中的配置错误,所以无法将日志输出到指定的位置,从而导致了这个错误。 五、总结 通过以上分析,我们可以看出,环境配置问题和日志配置错误都是非常严重的问题,如果不及时处理,就会导致Dubbo无法正常运行,从而影响我们的工作。所以呢,咱们得好好学习、掌握这些知识点,这样一来,在实际工作中碰到问题时,就能更有效率地避开陷阱,解决麻烦了。同时,我们也应该养成良好的编程习惯,比如定期检查环境变量和日志配置文件,确保它们的正确性。
2023-06-21 10:00:14
435
春暖花开-t
转载文章
...ng;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
转载
转载文章
...oadAction.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
转载
转载文章
...ok;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;import org.htmlparser.Node;import org.htmlparser.NodeFilter;import org.htmlparser.Parser;import org.htmlparser.filters.NodeClassFilter;import org.htmlparser.filters.OrFilter;import org.htmlparser.tags.LinkTag;import org.htmlparser.tags.TableTag;import org.htmlparser.util.NodeList;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;public class HtmlLook {private static String ENCODE = "UTF-8";public static void main(String[] args) {String szContent = openFile( "d:/index.html");try {Document doc = Jsoup.parse(szContent);Elements elList=doc.getElementsByAttributeValue("id","vulDataTable");szContent=elList.outerHtml();Parser parser = Parser.createParser(szContent, ENCODE);NodeFilter[] filters = new NodeFilter[2];filters[0] = new NodeClassFilter(TableTag.class); filters[1] = new NodeClassFilter(LinkTag.class);NodeFilter filter =new OrFilter (filters);NodeList list = parser.extractAllNodesThatMatch(filter);String ldName="";String ldJianjie="";for (int i = 0; i < list.size(); i++) { Node node = list.elementAt(i); if(node instanceof LinkTag){String nodeHtml=node.toHtml();if(nodeHtml.contains("onclick")&&nodeHtml.contains("vul-")){if(!"".equals(ldName)&&!"".equals(ldJianjie)){//提交数据System.out.println("---commit---漏洞名称-------"+ldName);System.out.println("---commit---漏洞简介-------"+ldJianjie);ldName="";ldJianjie="";}String level="";if(nodeHtml.contains("vul-vh")){level="高危漏洞";}else if(nodeHtml.contains("vul-vm")){level="中危漏洞";}else if(nodeHtml.contains("vul-vl")){level="低危漏洞";}ldName=getLinkTagContent(nodeHtml)+"-----"+level+"------";// System.out.println("---漏洞名称-----"+getLinkTagContent(nodeHtml)+"-----"+level+"------");} }else{ldJianjie=getTableTagContent(node.toHtml());} } } catch (Exception e) {e.printStackTrace();} }/ 提取文件里面的文本信息 @param szFileName @return/public static String openFile(String szFileName) {try {BufferedReader bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(szFileName)), ENCODE));String szContent = "";String szTemp;while ((szTemp = bis.readLine()) != null) {szContent += szTemp + "\n";}bis.close();return szContent;} catch (Exception e) {return "";} }/ 提取标签<a>a</a>内的内容 return a;/public static String getLinkTagContent(String link){String content="";Pattern pattern = Pattern.compile("<a[^>]>(.?)</a>");Matcher matcher = pattern.matcher(link);if(matcher.find()){content=matcher.group(1);}return content;}/ 解析Table标签内的东西 @param table/public static String getTableTagContent(String table){Map<String,String> conMap=new HashMap<String,String>();String content="";Document doc = Jsoup.parse(table);Elements elList=doc.getElementsByAttributeValue("class","cmn_table plumb");Element el=elList.first();Elements trLists = el.select("tr");for (int i = 0; i < trLists.size(); i++) {Elements tds = trLists.get(i).select("td");String key="";String val="";for (int j = 0; j < tds.size(); j++) {String text = tds.get(j).text();if(j==0){key=text; }else{val=text; } }conMap.put(key, val);content+="|"+key+"-"+val;// System.out.println(key+"-"+val);}return content;} } 本篇文章为转载内容。原文链接:https://blog.csdn.net/zhaoguoshuai91/article/details/51802116。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-07-19 10:42:16
295
转载
转载文章
...g; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.; public class swingJpanelQieHuan extends JFrame{ public static JPanel jpRed,jpPink,jpBlueRightBottom1, jpGreenRightBottom2; public static JButton anNiu1,anNiu2; JLabel JLabel1; public static JLabel JLabel2; public swingJpanelQieHuan(){ this.setLayout(null); this.setSize(700,700); this.setLocationRelativeTo(null); jpRed=new JPanel(); jpPink=new JPanel(); jpBlueRightBottom1=new JPanel(); jpGreenRightBottom2=new JPanel(); jpRed.setLayout(null); anNiu1=new JButton("点赞界面"); anNiu2=new JButton("三连关注界面"); anNiu1.setBounds(150,30,120,30); anNiu2.setBounds(300,30,120,30); anNiu1.addActionListener(new swingJpanelShiJian(this)); anNiu2.addActionListener(new swingJpanelShiJian(this)); jpRed.add(anNiu1);jpRed.add(anNiu2); jpRed.setBorder(BorderFactory.createLineBorder(Color.red)); jpPink.setBorder(BorderFactory.createLineBorder(Color.pink)); jpBlueRightBottom1.setBorder (BorderFactory.createLineBorder(Color.blue)); jpGreenRightBottom2.setBorder (BorderFactory.createLineBorder(Color.green)); jpRed.setBounds(10,10,600,150); jpPink.setBounds(10,170,200,450); jpBlueRightBottom1.setBounds(220, 170, 380, 450); jpGreenRightBottom2.setBounds(220, 170, 380, 450); JLabel1 = new JLabel(); JLabel2=new JLabel(); JLabel1. setIcon(new ImageIcon("img//1.png")); JLabel2. setIcon(new ImageIcon("img//2.png")); jpBlueRightBottom1.add(JLabel1); jpGreenRightBottom2.add(JLabel2); this.add(jpRed);this.add(jpPink); this.add(jpGreenRightBottom2); this.add(jpBlueRightBottom1); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } class swingJpanelShiJian implements ActionListener{ //jieShou接收 //chuangTi窗体 public static swingJpanelQieHuan jieShou; public swingJpanelShiJian(swingJpanelQieHuan chuangTi){ jieShou=chuangTi; } @Override public void actionPerformed(ActionEvent arg0) { String neiRong=arg0.getActionCommand(); if(neiRong.equals("点赞界面")){ jieShou.jpBlueRightBottom1.setVisible(true); jieShou.jpGreenRightBottom2.setVisible(false); }else if(neiRong.equals("三连关注界面")){ jieShou.jpBlueRightBottom1.setVisible(false); jieShou.jpGreenRightBottom2.setVisible(true); } } } JTree树形控件点击内容弹出新的窗体 package swing; public class mains { public static void main(String[] args) { new swingJpanelQieHuan(); } } package swing; import java.awt.Color; import java.awt.Font; import javax.swing.; public class newDengLu extends JFrame{ public static JLabel lb1,lb2,lb3,lb4=null; public static JTextField txt1=null; public static JPasswordField pwd=null; public static JComboBox com=null; public static JButton btn1,btn2=null; public newDengLu(){ this.setTitle("诗书画唱登录页面"); this.setLayout(null); this.setSize(500,400); this.setLocationRelativeTo(null); lb1=new JLabel("用户名"); lb2=new JLabel("用户密码"); lb3=new JLabel("用户类型"); lb4=new JLabel("登录窗体"); Font f=new Font("微软雅黑",Font.BOLD,35); lb4.setFont(f); lb4.setForeground(Color.red); lb4.setBounds(160,30,140,40); lb1.setBounds(100, 100, 70,30); lb2.setBounds(100,140,70,30); lb3.setBounds(100,180,70,30); txt1=new JTextField(); txt1.setBounds(170,100,150,30); pwd=new JPasswordField(); pwd.setBounds(170,140,150,30); com=new JComboBox(); com.addItem("会员用户"); com.addItem("普通用户"); com.setBounds(170,180,150,30); btn1=new JButton("登录"); btn1.setBounds(130,220,70,30); btn2=new JButton("取消"); btn2.setBounds(240,220,70,30); this.add(lb1);this.add(lb2);this.add(lb3); this.add(txt1);this.add(pwd);this.add(com); this.add(btn1);this.add(btn2);this.add(lb4); //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } package swing; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; public class swingJpanelQieHuan extends JFrame{ public static JPanel jpRed,jpPinkLeft,jpBlueRightBottom1, jpGreenRightBottom2; public static JTree JTree1,JTree2; public static JButton anNiu1,anNiu2; public static JLabel JLabel1,JLabel2; public swingJpanelQieHuan(){ this.setLayout(null); this.setSize(700,700); this.setLocationRelativeTo(null); jpRed=new JPanel(); jpPinkLeft=new JPanel(); jpBlueRightBottom1=new JPanel(); jpGreenRightBottom2=new JPanel(); jpRed.setLayout(null); anNiu1=new JButton("点赞界面"); anNiu2=new JButton("三连关注界面"); anNiu1.setBounds(150,30,120,30); anNiu2.setBounds(300,30,120,30); anNiu1.addActionListener(new swingJpanelShiJian(this)); anNiu2.addActionListener(new swingJpanelShiJian(this)); jpRed.add(anNiu1);jpRed.add(anNiu2); jpRed.setBorder(BorderFactory.createLineBorder(Color.red)); jpPinkLeft.setBorder(BorderFactory.createLineBorder(Color.pink)); jpBlueRightBottom1.setBorder (BorderFactory.createLineBorder(Color.blue)); jpGreenRightBottom2.setBorder (BorderFactory.createLineBorder(Color.green)); jpRed.setBounds(10,10,600,150); jpPinkLeft.setBounds(10,170,200,450); jpBlueRightBottom1.setBounds(220, 170, 380, 450); jpGreenRightBottom2.setBounds(220, 170, 380, 450); JLabel1 = new JLabel(); JLabel2=new JLabel(); JLabel1. setIcon(new ImageIcon("img//1.png")); JLabel2. setIcon(new ImageIcon("img//2.png")); jpBlueRightBottom1.add(JLabel1); jpGreenRightBottom2.add(JLabel2); DefaultMutableTreeNode dmtn1 = new DefaultMutableTreeNode("图书管理"); DefaultMutableTreeNode dmtn_yonghu = new DefaultMutableTreeNode ("用户管理"); DefaultMutableTreeNode dmtnQieHuan = new DefaultMutableTreeNode ("切换到登录界面"); DefaultMutableTreeNode dmtn_yonghu_insert = new DefaultMutableTreeNode("增加用户"); DefaultMutableTreeNode dmtn_yonghu_update = new DefaultMutableTreeNode("修改用户"); DefaultMutableTreeNode dmtn_yonghu_delete = new DefaultMutableTreeNode("删除用户"); DefaultMutableTreeNode dmtn_yonghu_select = new DefaultMutableTreeNode("查询用户"); DefaultMutableTreeNode dmtn_jieyue = new DefaultMutableTreeNode("借阅管理"); DefaultMutableTreeNode dmtn_jieyue_insert = new DefaultMutableTreeNode("增加借阅信息"); DefaultMutableTreeNode dmtn_jieyue_update = new DefaultMutableTreeNode("修改借阅信息"); DefaultMutableTreeNode dmtn_jieyue_delete = new DefaultMutableTreeNode("删除借阅信息"); DefaultMutableTreeNode dmtn_jieyue_select = new DefaultMutableTreeNode("查询借阅信息"); dmtn_yonghu.add(dmtnQieHuan); dmtn_yonghu.add(dmtn_yonghu_insert); dmtn_yonghu.add(dmtn_yonghu_update); dmtn_yonghu.add(dmtn_yonghu_delete); dmtn_yonghu.add(dmtn_yonghu_select); dmtn_jieyue.add(dmtn_jieyue_insert); dmtn_jieyue.add(dmtn_jieyue_update); dmtn_jieyue.add(dmtn_jieyue_delete); dmtn_jieyue.add(dmtn_jieyue_select); dmtn1.add(dmtn_yonghu); dmtn1.add(dmtn_jieyue); JTree1 = new JTree(dmtn1); JTree1.addTreeSelectionListener(new swingJpanelShiJian(this)); JTree1.setBackground(Color.white); jpPinkLeft.setBackground(Color.white); //JTree1.setBounds(10,170,200,450);在这里是一句没效果的代码 jpPinkLeft.add(JTree1); this.add(jpRed);this.add(jpPinkLeft); this.add(jpGreenRightBottom2); this.add(jpBlueRightBottom1); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } class swingJpanelShiJian implements ActionListener, TreeSelectionListener{ //jieShou接收 //chuangTi窗体 public static swingJpanelQieHuan jieShou; public swingJpanelShiJian(swingJpanelQieHuan chuangTi){ jieShou=chuangTi; } @Override public void actionPerformed(ActionEvent arg0) { String neiRong=arg0.getActionCommand(); if(neiRong.equals("点赞界面")){ jieShou.jpBlueRightBottom1.setVisible(true); jieShou.jpGreenRightBottom2.setVisible(false); }else if(neiRong.equals("三连关注界面")){ jieShou.jpBlueRightBottom1.setVisible(false); jieShou.jpGreenRightBottom2.setVisible(true); } } @Override public void valueChanged(TreeSelectionEvent arg0) { DefaultMutableTreeNode str = (DefaultMutableTreeNode) jieShou.JTree1 .getLastSelectedPathComponent(); if (str.toString().equals("切换到登录界面")) { new newDengLu(); } else { } } } JTable初始化表格 package swing; public class mains { public static void main(String[] args) { new swingBiaoGe(); } } package swing; import java.util.Vector; import javax.swing.; import javax.swing.table.DefaultTableModel; public class swingBiaoGe extends JFrame{ //要声明 : 装载内容的容器,table的控件, 容器的标题, 容器的具体的内容。 public static JTable biaoGe=null;//JTable为表格的控件 //要声明装载内容的容器,如下: public static DefaultTableModel DTM=null; //Vector中: //一个放标题,一个放内容 //>表示只接受集合的类型 Vector biaoTi; Vector> neiRong; public swingBiaoGe(){ this.setLayout(null); this.setSize(600,600); this.setLocationRelativeTo(null); //给标题赋值: biaoTi=new Vector(); biaoTi.add("编号");biaoTi.add("姓名"); biaoTi.add("性别");biaoTi.add("年龄"); //给内容赋值: neiRong=new Vector>(); for(int i=0;i<5;i++){ Vector v=new Vector(); v.add("编号"+(i+6));v.add("诗书画唱"+(i+6)); v.add("性别"+(i+6));v.add("年龄"+(i+6)); neiRong.add(v); } //将内容添加到装载内容的容器中: DTM=new DefaultTableModel(neiRong,biaoTi); DTM=new DefaultTableModel(neiRong,biaoTi) { @Override public boolean isCellEditable(int a, int b) { return false; } }; biaoGe=new JTable(DTM); //设置滚动条: JScrollPane jsp=new JScrollPane(biaoGe); jsp.setBounds(10,10,400,400); this.add(jsp); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } JTable初始化数据,数据要求链接JDBC获取 create database yonghu select from shangpin; select from sp_Type; create table sp_Type( sp_TypeID int primary key identity(1,1), sp_TypeName varchar(100) not null ); insert into sp_Type values('水果'); insert into sp_Type values('零食'); insert into sp_Type values('小吃'); insert into sp_Type values('日常用品'); create table shangpin( sp_ID int primary key identity(1,1), sp_Name varchar(100) not null, sp_Price decimal(10,2) not null, sp_TypeID int, sp_Jieshao varchar(300) ); insert into shangpin values('苹果',12,1,'好吃的苹果'); insert into shangpin values('香蕉',2,1,'好吃的香蕉'); insert into shangpin values('橘子',4,1,'好吃的橘子'); insert into shangpin values('娃哈哈',3,2,'好吃营养好'); insert into shangpin values('牙刷',5,4,'全自动牙刷'); package SwingJdbc; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; public class biaoGe extends JFrame { class shiJian implements MouseListener, ActionListener { public biaoGe jieShou = null; public shiJian(biaoGe chuangTi) { this.jieShou = chuangTi; } @Override public void actionPerformed(ActionEvent arg0) { String name = jieShou.wenBenKuangName.getText(); String price = jieShou.wenBenKuangPrice.getText(); String type = jieShou.wenBenKuangTypeId.getText(); String jieshao = jieShou.wenBenKuangJieShao. getText(); String sql = "insert into shangpin values('" + name + "'" + ", " + price + "," + type + ",'" + jieshao + "')"; if (DBUtils.ZSG(sql)) { JOptionPane.showMessageDialog(null, "增加成功"); jieShou.chaxunchushihua(); } else { JOptionPane.showMessageDialog(null, "出现了未知的错误,增加失败"); } } @Override public void mouseClicked(MouseEvent arg0) { if (arg0.getClickCount() == 2) { int row = jieShou.biaoGe1.getSelectedRow(); jieShou.wenBenKuangBianHao .setText(jieShou.biaoGe1.getValueAt( row, 0).toString()); jieShou.wenBenKuangName .setText(jieShou.biaoGe1.getValueAt( row, 1).toString()); jieShou.wenBenKuangPrice .setText(jieShou.biaoGe1.getValueAt( row, 2).toString()); jieShou.wenBenKuangTypeId .setText(jieShou.biaoGe1.getValueAt( row, 3).toString()); jieShou.wenBenKuangJieShao .setText(jieShou.biaoGe1.getValueAt( row, 4).toString()); } if (arg0.isMetaDown()) { int num = JOptionPane.showConfirmDialog(null, "是否确认删除这条信息?"); if (num == 0) { int row = jieShou.biaoGe1 .getSelectedRow(); String sql = "delete shangpin where sp_id=" + jieShou.biaoGe1.getValueAt( row, 0) + ""; if (DBUtils.ZSG(sql)) { JOptionPane.showMessageDialog(null, "册除成功"); jieShou.chaxunchushihua(); } else { JOptionPane.showMessageDialog(null, "出现了未知的错误,请重试"); } } } } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } static JButton zengJiaAnNiu = null; static DefaultTableModel biaoGeMoXing1 = null; static JScrollPane gunDongTiao = null; static JTable biaoGe1 = null; static JLabel wenZiBianHao, wenZiName, wenZiPrice, wenZiTypeId, wenZiJieShao; static JTextField wenBenKuangBianHao, wenBenKuangName, wenBenKuangPrice, wenBenKuangTypeId, wenBenKuangJieShao; static Vector BiaoTiJiHe = null; static Vector> NeiRongJiHe = null; JPanel mianBan1, mianBan2 = null; public biaoGe() { this.setTitle("登录后的界面"); this.setSize(800, 600); this.setLayout(null); this.setLocationRelativeTo(null); wenZiBianHao = new JLabel("编号"); wenZiName = new JLabel("名称"); wenZiPrice = new JLabel("价格"); wenZiTypeId = new JLabel("类型ID"); wenZiJieShao = new JLabel("介绍"); zengJiaAnNiu = new JButton("添加数据"); zengJiaAnNiu.setBounds(530, 390, 100, 30); zengJiaAnNiu.addActionListener(new shiJian(this)); this.add(zengJiaAnNiu); wenZiBianHao.setBounds(560, 100, 70, 30); wenZiName.setBounds(560, 140, 70, 30); wenZiPrice.setBounds(560, 180, 70, 30); wenZiTypeId.setBounds(560, 220, 70, 30); wenZiJieShao.setBounds(560, 260, 70, 30); this.add(wenZiBianHao); this.add(wenZiName); this.add(wenZiPrice); this.add(wenZiTypeId); this.add(wenZiJieShao); wenBenKuangBianHao = new JTextField(); wenBenKuangBianHao.setEditable(false); wenBenKuangName = new JTextField(); wenBenKuangPrice = new JTextField(); wenBenKuangTypeId = new JTextField(); wenBenKuangJieShao = new JTextField(); wenBenKuangBianHao.setBounds(640, 100, 130, 30); wenBenKuangName.setBounds(640, 140, 130, 30); wenBenKuangPrice.setBounds(640, 180, 130, 30); wenBenKuangTypeId.setBounds(640, 220, 130, 30); wenBenKuangJieShao.setBounds(640, 260, 130, 30); this.add(wenBenKuangBianHao); this.add(wenBenKuangName); this.add(wenBenKuangPrice); this.add(wenBenKuangTypeId); this.add(wenBenKuangJieShao); biaoGeFengZhuangFangFa(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } //biaoGeFengZhuangFangFa表格的封装方法 private void biaoGeFengZhuangFangFa() { BiaoTiJiHe = new Vector(); BiaoTiJiHe.add("编号"); BiaoTiJiHe.add("名称"); BiaoTiJiHe.add("价格"); BiaoTiJiHe.add("类型"); BiaoTiJiHe.add("介绍"); String sql = "select from shangpin"; ResultSet res = DBUtils.Select(sql); try { NeiRongJiHe = new Vector>(); while (res.next()) { Vector v = new Vector(); v.add(res.getInt("sp_ID")); v.add(res.getString("sp_Name")); v.add(res.getDouble("sp_price")); v.add(res.getInt("sp_TypeID")); v.add(res.getString("sp_Jieshao")); NeiRongJiHe.add(v); } biaoGeMoXing1 = new DefaultTableModel(NeiRongJiHe, BiaoTiJiHe) { @Override public boolean isCellEditable(int a, int b) { return false; } }; biaoGe1 = new JTable(biaoGeMoXing1); biaoGe1.addMouseListener(new shiJian(this)); biaoGe1.setBounds(0, 0, 500, 500); gunDongTiao= new JScrollPane(biaoGe1); gunDongTiao .setBounds(0, 0, 550, 150); mianBan1 = new JPanel(); mianBan1.add(gunDongTiao ); mianBan1.setBounds(0, 0, 550, 250); this.add(mianBan1); } catch (SQLException e) { e.printStackTrace(); } } public void chaxunchushihua() { if (this.mianBan1 != null) { this.remove(mianBan1); } biaoGeFengZhuangFangFa(); // 释放资源:this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } package SwingJdbc; import java.sql.; public class DBUtils { static Connection con=null; static Statement sta=null; static ResultSet res=null; //在静态代码块中执行 static{ try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //封装链接数据库的方法 public static Connection getCon(){ if(con==null){ try { con=DriverManager.getConnection ("jdbc:sqlserver://localhost;databaseName=yonghu","qqq","123"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return con; } //查询的方法 public static ResultSet Select(String sql){ con=getCon();//建立数据库链接 try { sta=con.createStatement(); res=sta.executeQuery(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return res; } //增删改查的方法 //返回int类型的数据 public static boolean ZSG(String sql){ con=getCon();//建立数据库链接 boolean b=false; try { sta=con.createStatement(); int num=sta.executeUpdate(sql); //0就是没有执行成功,大于0 就成功了 if(num>0){ b=true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return b; } } package SwingJdbc; public class mains { public static void main(String[] args) { new biaoGe(); } } 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_39929646/article/details/114190817。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-18 08:36:23
525
转载
Consul
...基本概念 - 服务(Service):在Consul中,服务被定义为一组运行在同一或不同节点上的实例。 - 服务注册(Service Registration):服务需要主动向Consul注册自己,提供诸如服务名称、标签、地址和端口等信息。 - 服务发现(Service Discovery):Consul通过服务标签和健康检查结果,为客户端提供服务的动态位置信息。 3. 安装与配置Consul 首先,确保你的开发环境已经安装了Go语言环境。然后,可以使用官方提供的脚本或者直接从源码编译安装Consul。接下来,配置Consul的基本参数,如监听端口、数据目录等。对于生产环境,建议使用持久化存储(如Etcd、KV Store)来存储状态信息。 bash 使用官方脚本安装 curl -s https://dl.bintray.com/hashicorp/channels | bash -s -- -b /usr/local/bin consul 启动Consul服务 consul server 4. 使用Consul进行服务注册与发现 服务注册是Consul中最基础的操作之一。通过简单的HTTP API,服务可以将自己的信息(如服务名、IP地址、端口)发送给Consul服务器,完成注册过程。 go package main import ( "fmt" "net/http" "os" "github.com/hashicorp/consul/api" ) func main() { c, err := api.NewClient(&api.Config{ Address: "localhost:8500", }) if err != nil { fmt.Println("Error creating Consul client:", err) os.Exit(1) } // 注册服务 svc := &api.AgentService{ ID: "example-service", Name: "Example Service", Tags: []string{"example", "service"}, Address: "127.0.0.1", Port: 8080, Weights: []float64{1.0}, Meta: map[string]string{"version": "v1"}, Check: &api.AgentServiceCheck{ HTTP: "/healthcheck", Interval: "10s", DeregisterCriticalServiceAfter: "5m", }, } // 发送注册请求 resp, err := c.Agent().ServiceRegister(svc) if err != nil { fmt.Println("Error registering service:", err) os.Exit(1) } fmt.Println("Service registered:", resp.Service.ID) } 服务发现则可以通过查询Consul的服务列表来完成。客户端可以通过Consul的API获取所有注册的服务信息,并根据服务的标签和健康状态来选择合适的服务进行调用。 go package main import ( "fmt" "time" "github.com/hashicorp/consul/api" ) func main() { c, err := api.NewClient(&api.Config{ Address: "localhost:8500", }) if err != nil { fmt.Println("Error creating Consul client:", err) os.Exit(1) } // 查询特定标签的服务 opts := &api.QueryOptions{ WaitIndex: 0, } // 通过服务名称和标签获取服务列表 services, _, err := c.Health().ServiceQuery("example-service", "example", opts) if err != nil { fmt.Println("Error querying services:", err) os.Exit(1) } for _, svc := range services { fmt.Printf("Found service: %s (ID: %s, Address: %s:%d)\n", svc.Service.Name, svc.Service.ID, svc.Service.Address, svc.Service.Port) } } 5. 性能与扩展性 Consul通过其设计和优化,能够处理大规模的服务注册和发现需求。通过集群部署,可以进一步提高系统的可用性和性能。同时,Consul支持多数据中心部署,满足了跨地域服务部署的需求。 6. 总结 Consul作为一个强大的服务发现工具,不仅提供了简单易用的API接口,还具备高度的可定制性和扩展性。哎呀,你知道吗?把Consul整合进服务网格里头,就像给你的交通系统装上了智能导航!这样一来,各个服务之间的信息交流不仅快得跟风一样,还超级稳,就像在高速公路上开车,既顺畅又安全。这可是大大提升了工作效率,让咱们的服务运行起来更高效、更可靠!随着微服务架构的普及,Consul成为了构建现代服务网格不可或缺的一部分。兄弟,尝试着运行这些示例代码,你会发现如何在真正的工程里用Consul搞服务发现其实挺好玩的。就像是给你的编程技能加了个新魔法,让你在项目中找服务就像玩游戏一样简单!这样一来,你不仅能把这玩意儿玩得溜,还能深刻体会到它的魅力和实用性。别担心,跟着我,咱们边做边学,保证让你在实际操作中收获满满!
2024-08-05 15:42:27
34
青春印记
Sqoop
...: bash java.lang.ClassNotFoundException: com.mysql.jdbc.MySQLBlobInputStream 这是因为Sqoop在默认配置下可能并不支持所有数据库特定的内置类型,尤其是那些非标准的或者用户自定义的类型。 3. 解决方案详述 3.1 自定义jdbc驱动类映射 为了解决上述问题,我们需要帮助Sqoop识别并正确处理这些特定的列类型。Sqoop这个工具超级贴心,它让用户能够自由定制JDBC驱动的类映射。你只需要在命令行耍个“小魔法”,也就是加上--map-column-java这个参数,就能轻松指定源表中特定列在Java环境下的对应类型啦,就像给不同数据类型找到各自合适的“变身衣裳”一样。 例如,对于上述的MEDIUMBLOB类型,我们可以将其映射为Java的BytesWritable类型: bash sqoop import \ --connect jdbc:mysql://localhost/mydatabase \ --table my_table \ --columns 'id, medium_blob_column' \ --map-column-java medium_blob_column=BytesWritable \ --target-dir /user/hadoop/my_table_data 3.2 扩展Sqoop的JDBC驱动 另一种更为复杂但更为彻底的方法是扩展Sqoop的JDBC驱动,实现对特定类型的支持。通常来说,这意味着你需要亲自操刀,写一个定制版的JDBC驱动程序。这个驱动要能“接班” Sqoop自带的那个驱动,专门对付那些原生驱动搞不定的数据类型转换问题。 java // 这是一个简化的示例,实际操作中需要对接具体的数据库API public class CustomMySQLDriver extends com.mysql.jdbc.Driver { // 重写方法以支持对MEDIUMBLOB类型的处理 @Override public java.sql.ResultSetMetaData getMetaData(java.sql.Connection connection, java.sql.Statement statement, String sql) throws SQLException { ResultSetMetaData metadata = super.getMetaData(connection, statement, sql); // 对于MEDIUMBLOB类型的列,返回对应的Java类型 for (int i = 1; i <= metadata.getColumnCount(); i++) { if ("MEDIUMBLOB".equals(metadata.getColumnTypeName(i))) { metadata.getColumnClassName(i); // 返回"java.sql.Blob" } } return metadata; } } 然后在Sqoop命令行中引用这个自定义的驱动: bash sqoop import \ --driver com.example.CustomMySQLDriver \ ... 4. 思考与讨论 尽管Sqoop在大多数情况下可以很好地处理数据迁移任务,但在面对一些特殊的数据库表列类型时,我们仍需灵活应对。无论是对JDBC驱动进行小幅度的类映射微调,还是大刀阔斧地深度定制,最重要的一点,就是要摸透Sqoop的工作机制,搞清楚它背后是怎么通过底层的JDBC接口,把那些Java对象两者之间巧妙地对应和映射起来的。想要真正玩转那个功能强大的Sqoop数据迁移神器,就得在实际操作中不断摸爬滚打、学习积累。这样,才能避免被“ClassNotFoundException”这类让人头疼的小插曲绊住手脚,顺利推进工作进程。
2023-04-02 14:43:37
83
风轻云淡
Java
Java中的错误处置机制是指一种基于面向对象的错误处置方式,通过引发异常来处置代码中可能发生的异常情况,以确保程序在出现错误时有良好的崩溃处置机制,提高程序的抗错能力。错误处置机制划分为两种:Error和Exception,其中Error代表系统层次错误,一般是由底层资源不足引起的,无法修复,一般不用捕获;而Exception代表程序运行时出现错误,可以被程序捕捉并及时处置。 try { //执行可能会引发异常的代码 } catch (ExceptionType e) { //处置异常 } finally { //无论是否有异常都执行 } Java中的异常结构主要划分为三个部分:try、catch和finally。try语句块中是我们希望正常执行的代码,可能会引发异常的代码需要放到try语句块中;catch语句用于捕获异常,当try语句中的代码发现异常时,就会将异常引发,然后被catch语句捕获,从而进行适当的处置或日志记录;finally语句中的代码不管try语句块中是否发生异常,都一定会被执行,一般用于释放资源或做一些必要的清理工作。 throw new ExceptionType("Error Message!"); 除了try/catch/finally外,Java中还提供了throw机制,即手动引发异常。当程序发觉出现错误时,我们可以通过throw引发一个异常实例,如果某个方法遇到了引发的异常实例,就会将异常传播到该方法的调用者,直至catch语句捕捉异常。
2023-08-12 22:57:07
316
编程狂人
HTML
...使用体验。例如,借助Service Workers和离线缓存策略,传智书城这样的在线商城可以实现快速加载和离线访问书籍信息,显著提高用户留存率和购买转化率。 此外,在SEO优化方面,Google等搜索引擎不断更新算法,更加重视网页结构的语义化以及移动设备友好性。因此,对HTML5语义标签如 、 、 等的有效运用,以及响应式设计的实践,都是现今及未来网页开发中不可忽视的关键要素。 综上所述,尽管HTML作为网站开发基石的重要性不言而喻,但紧跟行业前沿动态,适时引入新的开发技术和优化手段,才是确保像传智书城这样的在线平台始终保持竞争力的核心所在。
2023-08-22 12:19:23
463
算法侠
Java
Java是一种常见的编程语言,在很多应用场景中都有广泛的应用。其中,Write和Login两个关键词是我们在Java中经常使用的函数名。下面将详细讲解这两个函数的用法和实现。 Write函数 public void Write(String message, OutputStream outputStream) throws IOException Write函数用于将给定的字符串写入指定的输出流中。通常情况下,我们可以使用该函数来将数据写入到文件、网络或控制台等输出设备中。 该函数共有两个参数: message:要写入的字符串。 outputStream:要写入数据的输出流。 下面是一个简单的使用示例: try { OutputStream outputStream = new FileOutputStream("example.txt"); String message = "这是一条测试数据"; Write(message, outputStream); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } Login函数 public void Login(String username, String password) throws LoginException Login函数用于验证给定的用户名和密码是否正确。通常情况下,我们可以使用该函数来进行用户认证,保护系统安全。 该函数共有两个参数: username:要验证的用户名。 password:要验证的密码。 如果验证成功,那么该函数将正常返回;否则,会抛出一个LoginException异常。下面是一个简单的使用示例: try { String username = "test"; String password = "123456"; Login(username, password); System.out.println("登录成功!"); } catch (LoginException e) { e.printStackTrace(); } 通过上述介绍,我们可以看出,Write和Login函数都是Java中常用的函数,它们分别实现了数据输出和用户认证的功能。在实际的Java应用中,我们可以结合具体的业务场景,充分发挥它们的作用,提高系统的性能和安全。
2023-08-11 21:09:32
331
代码侠
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
tar -cvzf archive.tar.gz dir
- 压缩目录至gzip格式的tar包。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"