首页 文章 精选 留言 我的

精选列表

搜索[Vite构建],共10000篇文章
优秀的个人博客,低调大师

Docker-Swarm-下-NATS-集群的构建与使用

NATS 是一个开源的、轻量级的、高性能的分布式消息通信系统,实现了高可伸缩性和优雅的发布/订阅模型。 NATS 适合云基础设施的消息通信系统、物联网设备消息通信和微服务架构。 环境准备 三台服务器,建立 Docker Swarm 集群,一个 Manager,两个 Worker。 docker 版本:17-09 nats 版本:1.0.4 Nats 集群架构设计 搭建集群 1、【Manager】创建集群网络 dockernetworkcreate-doverlay--attachablemongo --attachable 允许其他容器加入此网络 2、创建 Nats 集群 2.1、【Manager】创建 stack.yml version:'3.3' services: nats1: image:registry.docker-cn.com/library/nats command:--clusternats://0.0.0.0:5222-routesnats://nats2:5222,nats://nats3:5222 ports: -4222 networks: -nats deploy: restart_policy: condition:on-failure placement: constraints: -node.hostname==manager nats2: image:registry.docker-cn.com/library/nats command:--clusternats://0.0.0.0:5222-routesnats://nats1:5222,nats://nats3:5222 ports: -4222 networks: -nats deploy: restart_policy: condition:on-failure placement: constraints: -node.hostname==worker1 nats3: image:registry.docker-cn.com/library/nats command:--clusternats://0.0.0.0:5222-routesnats://nats1:5222,nats2:5222 ports: -4222 networks: -nats deploy: restart_policy: condition:on-failure placement: constraints: -node.hostname==worker2 networks: nats: external:true 2.2、【Manager】启动集群 dockerstackdeploy-cstack.ymlnats 2.3、【Manager】查看服务的启动情况 dockerservicels 3、连接集群 外部【用于测试】:查看端口随机的端口映射(netstat -ntlp),一般为 30000~30002,连接时指定多个URL: nats://managerIP:30000 nats://managerIP:30001 nats://managerIP:30002 内部【限 nats 网络下的服务或容器】: nats://nats1:4222 nats://nats2:4222 nats://nats3:4222 在 Spring Boot 中连接 Nats 集群 1、 添加 Maven 依赖 <!--Nats--> <dependency> <groupId>com.github.cloudfoundry-community</groupId> <artifactId>nats-client</artifactId> <version>0.6.7</version> </dependency> <!--SpringBoot配置处理--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> 2、 Nats 属性配置类 NatsProperties.java @ConfigurationProperties(prefix="spring.nats") @Data publicclassNatsProperties{ privateString[]urls; } 3、Nats 自动配置类 NatsAutoConfiguration.java @org.springframework.context.annotation.Configuration @EnableConfigurationProperties(NatsProperties.class) @ConditionalOnClass(Nats.class) @Log4j2 publicclassNatsAutoConfiguration{ @Bean @ConditionalOnMissingBean(Nats.class) publicNatsnats(NatsPropertiesnatsProperties){ NatsConnectornatsConnector=newNatsConnector(); for(Stringurl:natsProperties.getUrls()){ natsConnector.addHost(url); } returnnatsConnector.connect(); } } 4、application.yml 配置示例 spring: nats: urls: -nats://192.168.99.100:30000 -nats://192.168.99.100:30001 -nats://192.168.99.100:30002 提示:如需在 yml 文件中提示自定义的配置属性,可以新建文件 resources/META-INF/spring.factories,内容如下:org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.ictgu.config.nats.NatsAutoConfiguration 5、使用 Nats 订阅发布消息 @Autowired privatenats.client.Natsnats; ... //订阅消息 publicvoidsubscribe(){ nats.subscribe("some.nats.subject",newMessageHandler(){ @Override publicvoidonMessage(Messagemessage){ System.out.println("Received:"+message); } }); } //发布消息 publicvoidsend(){ nats.subscribe("some.nats.subject","messagecontent"); } Docker视频教程学习地址:http://www.roncoo.com/course/view/3e9d9c48f76f4c698b8349d04b763467

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

从构建分布式秒杀系统聊聊验证码

前言 为了拦截大部分请求,秒杀案例前端引入了验证码。淘宝上很多人吐槽,等输入完秒杀活动结束了,对,结束了...... 当然了,验证码的真正作用是,有效拦截刷单操作,让羊毛党空手而归。 验证码 那么到底什么是验证码呢?验证码作为一种人机识别手段,其终极目的,就是区分正常人和机器的操作。我们常见的互联网注册、登录、发帖、领优惠券、投票等等应用场景,都有被机器刷造成各类损失的风险。 目前常见的验证码形式多为图片验证码,即数字、字母、文字、图片物体等形式的传统字符验证码。这类验证码看似简单易操作,但实际用户体验较差(参见12306网站),且随着OCR技术和打码平台的利用,图片比较容易被破解,被破解之后就形同虚设。 这里我们使用腾讯的智能人机安全验证码,告别传统验证码的单点防御,十道安全栅栏打造立体全面的安全验证,将黑产拒之门外。 场景 下面我们来瞅瞅验证码轻松解决了那些场景安全问题: 登录注册,为你防护撞库×××、阻止注册机批量注册 活动秒杀,有效拦截刷单操作,让羊毛党空手而归 点赞发帖,有效解决广告屠版、恶意灌水、刷票问题 数据保护,防止自动机、爬虫盗取网页内容和数据 申请 申请地址:https://007.qq.com/product.html 在线体验:https://007.qq.com/online.html 只要一个QQ就可以免费申请,对于一般的企业OA系统或者个人博客网站,验证码免费套餐足够了已经,具备以下特点: 2000次/小时安全防护 支持免验证+分级验证 三分钟快速接入 全功能配置后台 支持HTTPS 阈值内流量无广告 2000次/小时的安全防护,一般很少达到如此效果,当然了即时超出阈值,顶多也就是多个广告而已。 接入 快读接入:https://007.qq.com/quick-start.html 接入与帮助提供了多种客户端和服务端的接入案例,这里我们使用我们秒杀案例中最熟悉的Java语言来接入。 前端 引入JS: <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script> 页面元素: <!--点击此元素会自动激活验证码,不一定是button,其他标签也可以--> <!--id : 元素的id(必须)--> <!--data-appid : AppID(必须)--> <!--data-cbfn : 回调函数名(必须)--> <!--data-biz-state : 业务自定义透传参数(可选)--> <button id="TencentCaptcha" data-appid="*********" data-cbfn="callback">验证</button> JS回调: <script type="text/javascript"> window.callback = function(res){ console.log(res) // res(未通过验证)= {ret: 1, ticket: null} // res(验证成功) = {ret: 0, ticket: "String", randstr: "String"} if(res.ret === 0){ startSeckill(res) } } //后台验证ticket,并进入秒杀队列 function startSeckill(res){ $.ajax({ url : "startSeckill", type : 'post', data : {'ticket' : res.ticket,'randstr':res.randstr}, success : function(result) { //验证是否通过,提示用户 } }); } </script> 后端 @Api(tags = "秒杀商品") @RestController @RequestMapping("/seckillPage") public class SeckillPageController { @Autowired private ActiveMQSender activeMQSender; //自定义工具类 @Autowired private HttpClient httpClient; //这里自行配置参数 @Value("${qq.captcha.url}") private String url; @Value("${qq.captcha.aid}") private String aid; @Value("${qq.captcha.AppSecretKey}") private String appSecretKey; @RequestMapping("/startSeckill") public Result startSeckill(String ticket,String randstr,HttpServletRequest request) { HttpMethod method =HttpMethod.POST; MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>(); params.add("aid", aid); params.add("AppSecretKey", appSecretKey); params.add("Ticket", ticket); params.add("Randstr", randstr); params.add("UserIP", IPUtils.getIpAddr(request)); String msg = httpClient.client(url,method,params); /** * response: 1:验证成功,0:验证失败,100:AppSecretKey参数校验错误[required] * evil_level:[0,100],恶意等级[optional] * err_msg:验证错误信息[optional] */ //{"response":"1","evil_level":"0","err_msg":"OK"} JSONObject json = JSONObject.parseObject(msg); String response = (String) json.get("response"); if("1".equals(response)){ //进入队列、假数据而已 Destination destination = new ActiveMQQueue("seckill.queue"); activeMQSender.sendChannelMess(destination,1000+";"+1); return Result.ok(); }else{ return Result.error("验证失败"); } } } 自定义请求工具类 HttpClient: @Service public class HttpClient { public String client(String url, HttpMethod method, MultiValueMap<String, String> params){ RestTemplate client = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); // 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers); // 执行HTTP请求 ResponseEntity<String> response = client.exchange(url, HttpMethod.POST, requestEntity, String.class); return response.getBody(); } } 获取IP地址工具类 IPUtils : /** * IP地址 */ public class IPUtils { private static Logger logger = LoggerFactory.getLogger(IPUtils.class); /** * 获取IP地址 * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址 */ public static String getIpAddr(HttpServletRequest request) { String ip = null; try { ip = request.getHeader("x-forwarded-for"); if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } catch (Exception e) { logger.error("IPUtils ERROR ", e); } // 使用代理,则获取第一个IP地址 if (StringUtils.isEmpty(ip) && ip.length() > 15) { if (ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } return ip; } } 案例效果图 启动项目访问:http://localhost:8080/seckill/1000.shtml 定制接入 在系统登录的时候,我们需要先校验用户名以及密码,然后调用验证码操作,这里就需要我们定制接入了。 <!-- 项目中使用了Vue --> <div class="log_btn" @click="login" >登录</div> login: function () { //这里校验用户名以及密码 // 直接生成一个验证码对象 var captcha = new TencentCaptcha('2001344788', function(res) { if(res.ret === 0){//回调成功 var data = {'username':username,'password':password,'ticket':res.ticket,'randstr':res.randstr} $.ajax({ type: "POST", url: "sys/loginCaptcha", data: data, dataType: "json", success: function(result){ //校验是否成功 } }); } }); captcha.show(); // 显示验证码 }, 后台监控 腾讯后台还提供了简单实用的数据监控,如下: 小结 总体来说,系统接入人机验证码还是很方便的,并没有技术难点,难点已经被提供商封装,我们只需要简单的调用即可。 秒杀案例:https://gitee.com/52itstyle/spring-boot-seckill 演示案例(点击生成按钮):http://jichou.52itstyle.com

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

使用Spring Framework构建的应用程序面临严重缺陷

Spring框架,是用于开发Java Web的应用程序的。最近,其开发人员修补了三个漏洞,其中包括可用于远程代码执行的关键漏洞。 最严重的缺陷位于spring-messaging模块,它允许应用程序通过内存中的STOMP代理在WebSocket端点上公开STOMP(简单文本导向消息传递协议)。攻击者可以通过向代理发送特制的消息,利用该问题来获取远程代码执行。 该漏洞被命名为CVE-2018-1270,它影响了Spring Framework版本4.3.x和5.x,以及不再支持旧版本。强烈建议用户升级到新发布的Spring Framework 5.0.5或4.3.15。 第二个高级漏洞CVE-2018-1271,影响了用Spring MVC去服务静态资源如Windows上的文件系统里的CSS,JS的应用。该漏洞允许攻击者通过向特制URL发送请求来执行目录浏览,以访问受限资源。 凡是未使用Tomcat或WildFly作为其服务器的应用程序,或者未使用Windows文件的不受影响。 在Spring Framework 5.0.5和4.3.15,CVE-2018-1272中修补的第三个漏洞可能导致权限提升,但由于利用需要额外的攻击媒介,因此评级较低。 “当Spring MVC或Spring WebFlux服务器应用程序(服务器A)从远程客户端接收输入,然后使用该输入向另一个服务器(服务器B)发出多部分请求时,它可能会受到攻击,其中一个额外的多余部分插入服务器A的请求内容,导致服务器B对其预期的部分使用错误的值,“Spring开发人员指出。 但是,为了能成功,攻击者“必须能够猜测服务器A为服务器B的多部分请求选择的多部分边界值,这要求攻击者具有控制服务器或查看服务器的能力。” Spring具有模块化架构,很受应用程序开发人员的欢迎,尤其是在企业领域。根据2016年对2040名参与者的调查结果,Spring MVC和Spring Boot是Java开发人员中最受欢迎的两个Web框架,分别被43%和29%的受访者使用。

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

Spring Cloud构建微服务架构-创建“服务提供方”

下面我们创建提供服务的客户端,并向服务注册中心注册自己。本文我们主要介绍服务的注册与发现,所以我们不妨在服务提供方中尝试着提供一个接口来获取当前所有的服务信息。 首先,创建一个基本的Spring Boot应用。命名为eureka-client,在pom.xml中,加入如下配置: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Dalston.SR1</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> 其次,实现/dc请求处理接口,通过DiscoveryClient对象,在日志中打印出服务实例的相关内容。 @RestController public class DcController { @Autowired DiscoveryClient discoveryClient; @GetMapping("/dc") public String dc() { String services = "Services: " + discoveryClient.getServices(); System.out.println(services); return services; } } 最后在应用主类中通过加上@EnableDiscoveryClient注解,该注解能激活Eureka中的DiscoveryClient实现,这样才能实现Controller中对服务信息的输出。 @EnableDiscoveryClient @SpringBootApplication public class Application { public static void main(String[] args) { new SpringApplicationBuilder( ComputeServiceApplication.class) .web(true).run(args); } } 我们在完成了服务内容的实现之后,再继续对application.properties做一些配置工作,具体如下: spring.application.name=eureka-client server.port=2001 eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/ 通过spring.application.name属性,我们可以指定微服务的名称后续在调用的时候只需要使用该名称就可以进行服务的访问。eureka.client.serviceUrl.defaultZone属性对应服务注册中心的配置内容,指定服务注册中心的位置。为了在本机上测试区分服务提供方和服务注册中心,使用server.port属性设置不同的端口。 当然,我们也可以通过直接访问eureka-client服务提供的/dc接口来获取当前的服务清单 中,方括号中的eureka-client就是通过Spring Cloud定义的DiscoveryClient接口在eureka的实现中获取到的所有服务清单。由于Spring Cloud在服务发现这一层做了非常好的抽象,所以,对于上面的程序,我们可以无缝的从eureka的服务治理体系切换到consul的服务治理体系中区。 从现在开始,我这边会将近期研发的springcloud微服务云架构的搭建过程和精髓记录下来,帮助更多有兴趣研发spring cloud框架的朋友,希望可以帮助更多的好学者。大家来一起探讨spring cloud架构的搭建过程及如何运用于企业项目。 完整项目的源码来源 技术支持1791743380

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

Python构建企业微信自动消息转发服务端

一、背景 目前有在项目分组,就小组成员中,微信群消息回复较多的情况下,想根据组来转发特定消息,包含文字、图片、语言等。在此只是自己实现仅供参考,可以根据自身需求修改更多功能。 二、代码 2.1 企业微信相关信息 企业ID:corpid 自建应用appid 自建应用secret 获取access_token api 发送消息 api 2.2 服务端部署运行环境:python 版本 2.7 git clone https://github.com/redhatxl/wechatmsg.git nohup python2.7 wechatmsg/wx_msg_server.py & 2.3 参考RUL: 获取access_token发送消息 2.4 代码 核心代码github地址 # flask 框架后台 def server_run(self): app = Flask(__name__) @app.route('/index', methods=['GET', 'POST']) def index(): wxcpt = WXBizMsgCrypt(self.sToken, self.sEncodingAESKey, self.sCorpID) # 获取url验证时微信发送的相关参数 sVerifyMsgSig = request.args.get('msg_signature') sVerifyTimeStamp = request.args.get('timestamp') sVerifyNonce = request.args.get('nonce') sVerifyEchoStr = request.args.get('echostr') # 验证url if request.method == 'GET': ret, sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr) print type(ret) print type(sEchoStr) if (ret != 0): print "ERR: VerifyURL ret:" + str(ret) sys.exit(1) return sEchoStr # 接收客户端消息 if request.method == 'POST': sReqMsgSig = sVerifyMsgSig sReqTimeStamp = sVerifyTimeStamp sReqNonce = sVerifyNonce sReqData = request.data print(sReqData) ret, sMsg = wxcpt.DecryptMsg(sReqData, sReqMsgSig, sReqTimeStamp, sReqNonce) print ret, sMsg if (ret != 0): print "ERR: DecryptMsg ret: " + str(ret) sys.exit(1) # 解析发送的内容并打印 xml_tree = ET.fromstring(sMsg) print('xml_tree is ', xml_tree) 消息内容发送 def _send_text_msg(self, content): data = { "touser": ('|').join(self.userid.split(',')), "toparty": ('|').join(self.partid.split(',')), # "toparty":int(self.partid), "msgtype": "text", "agentid": self.agent_id, "text": { "content": content }, "safe": 0 } try: response = requests.post(self.send_msg_url.format(self.access_token), json.dumps(data)) self.logoper.info(response.text) print(response.text) result_msg = json.loads(response.content)['errmsg'] return result_msg except Exception as e: self.logoper.info(e) 日志 def create_dir(self): """ 创建目录 :return: 文件名称 """ _LOGDIR = os.path.join(os.path.dirname(__file__), self.logdir_name) _TIME = time.strftime('%Y-%m-%d', time.gmtime()) + '-' _LOGNAME = _TIME + self.logfile_name LOGFILENAME = os.path.join(_LOGDIR, _LOGNAME) if not os.path.exists(_LOGDIR): os.mkdir(_LOGDIR) return LOGFILENAME def create_logger(self, logfilename): """ 创建logger对象 :param logfilename: :return: logger对象 """ logger = logging.getLogger() logger.setLevel(logging.INFO) handler = logging.FileHandler(logfilename) handler.setLevel(logging.INFO) formater = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formater) logger.addHandler(handler) return logger 配置文件 # 定义微信公众号信息 [common] # 企业微信企业ID corpid = wxe23xxxxxxxxxxx # 接收消息服务器配置 [recmsg] Token = mVNAAw3xxxxxxxxxxxxxxxxx EncodingAESKey = vwbKImxc3WPeE073xxxxxxxxxxxxxxxxxx # 自建应用信息 [appconfig] # 自建应用agentid agentid = 1000002 # 自建应用secret secret = 6HAGX7Muw36pv5anxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # 消息接收信息 # 消息接收用户id,如果多个用户用英文','隔开 userid = xuel|yaoy # 消息接收部门id,如果多个用英文','隔开 partid = 11 [urlconfig] # 获取应用token的api接口 get_access_token_url = https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={} # 发送消息api接口 send_msg_url = https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={} # 上传媒体api接口,获取mediaid upload_media_url = https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={}&type=image # 上传高清语音接口 upload_video_url = https://qyapi.weixin.qq.com/cgi-bin/media/get/jssdk?access_token={}&media_id={} [loginfo] #日志目录 logdir_name = logdir #日志文件名称 logfile_name = wechat_server.log 三、测试 在企业微信发送消息,可以修改配置文件制定转发到特定的群组,从而避免消息分流。启用应用API,设置回调地址测试发送消息查看接受消息 四、优化 后期可以配合数据库将每次获取的access_token 保存至数据库,待2小时过期后,再重新获取新的。 更多内容转发

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

从构建分布式秒杀系统聊聊WebSocket推送通知

前言 秒杀架构到后期,我们采用了消息队列的形式实现抢购逻辑,那么之前抛出过这样一个问题:消息队列异步处理完每个用户请求后,如何通知给相应用户秒杀成功? 场景映射 首先,我们举一个生活中比较常见的例子:我们去银行办理业务,一般会选择相关业务打印一个排号纸,然后就可以坐在小板凳上玩着手机,等待被小喇叭报号。当小喇叭喊到你所持有的号码,就可以拿着排号纸去柜台办理自己的业务。 这里,假设当我们取排号纸的时候,银行根据时间段内的排队情况,比较人性化的提示用户:排队人数较多,您是否继续等待?否的话我们可以换个时间段再来办理。 由此我们把生活场景映射到真实的秒杀业务逻辑中来: 我们可以把柜台比喻成商品下单处理逻辑单元 拿到排号纸说明你进入相应商品处理队列 拿到排号纸的请求直接返回前台,提示用户抢购进行中 排号纸进入队列后,等待商品业务处理逻辑 小喇叭叫到自己的排号相当于服务端通知用户秒杀成功,这时候可以进行支付逻辑 那些拿不到票号的同学,相当于队列已满直接返回秒杀失败 解决方案 通过上面的场景,我们很容易能够想到一种方案就是服务端通知,那么如何做到服务端异步通知的呢?下面,主角开始登场了,就是我们的Websocket。 WebSocket是HTML5开始提供的一种浏览器与服务器间进行全双工通讯的网络技术。依靠这种技术可以实现客户端和服务器端的长连接,双向实时通信。 特点: 异步、事件触发 可以发送文本,图片等流文件 数据格式比较轻量,性能开销小,通信高效 使用ws或者wss协议的客户端socket,能够实现真正意义上的推送功能 缺点: 部分浏览器不支持,浏览器支持的程度与方式有区别,需要各种兼容写法。 集成案例 由于我们的秒杀架构项目案例中使用了SpringBoot,因此集成webSocket也是相对比较简单的。 首先pom.xml引入以下依赖: <!-- webSocket 秒杀通知--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> WebSocketConfig 配置: /** * WebSocket配置 * 创建者 爪哇笔记 * 创建时间 2018年5月29日 */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } WebSocketServer 配置: @ServerEndpoint("/websocket/{userId}") @Component public class WebSocketServer { private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class); //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); //与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; //接收userId private String userId=""; /** * 连接建立成功调用的方法*/ @OnOpen public void onOpen(Session session,@PathParam("userId") String userId) { this.session = session; webSocketSet.add(this); //加入set中 addOnlineCount(); //在线数加1 log.info("有新窗口开始监听:"+userId+",当前在线人数为" + getOnlineCount()); this.userId=userId; try { sendMessage("连接成功"); } catch (IOException e) { log.error("websocket IO异常"); } } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); //从set中删除 subOnlineCount(); //在线数减1 log.info("有一连接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * @param message 客户端发送过来的消息*/ @OnMessage public void onMessage(String message, Session session) { log.info("收到来自窗口"+userId+"的信息:"+message); //群发消息 for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } /** * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("发生错误"); error.printStackTrace(); } /** * 实现服务器主动推送 */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 群发自定义消息 * */ public static void sendInfo(String message,@PathParam("userId") String userId){ log.info("推送消息到窗口"+userId+",推送内容:"+message); for (WebSocketServer item : webSocketSet) { try { //这里可以设定只推送给这个userId的,为null则全部推送 if(userId==null) { item.sendMessage(message); }else if(item.userId.equals(userId)){ item.sendMessage(message); } } catch (IOException e) { continue; } } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } } KafkaConsumer 消费配置,通知用户是否秒杀成功: /** * 消费者 spring-kafka 2.0 + 依赖JDK8 * @author 科帮网 By https://blog.52itstyle.com */ @Component public class KafkaConsumer { @Autowired private ISeckillService seckillService; private static RedisUtil redisUtil = new RedisUtil(); /** * 监听seckill主题,有消息就读取 * @param message */ @KafkaListener(topics = {"seckill"}) public void receiveMessage(String message){ //收到通道的消息之后执行秒杀操作 String[] array = message.split(";"); if(redisUtil.getValue(array[0])!=null){//control层已经判断了,其实这里不需要再判断了 Result result = seckillService.startSeckil(Long.parseLong(array[0]), Long.parseLong(array[1])); if(result.equals(Result.ok())){ WebSocketServer.sendInfo(array[0].toString(), "秒杀成功");//推送给前台 }else{ WebSocketServer.sendInfo(array[0].toString(), "秒杀失败");//推送给前台 redisUtil.cacheValue(array[0], "ok");//秒杀结束 } }else{ WebSocketServer.sendInfo(array[0].toString(), "秒杀失败");//推送给前台 } } } webSocket.js 前台通知逻辑: $(function(){ socket.init(); }); var basePath = "ws://localhost:8080/seckill/"; socket = { webSocket : "", init : function() { //userId:自行追加 if ('WebSocket' in window) { webSocket = new WebSocket(basePath+'websocket/1'); } else if ('MozWebSocket' in window) { webSocket = new MozWebSocket(basePath+"websocket/1"); } else { webSocket = new SockJS(basePath+"sockjs/websocket"); } webSocket.onerror = function(event) { alert("websockt连接发生错误,请刷新页面重试!") }; webSocket.onopen = function(event) { }; webSocket.onmessage = function(event) { var message = event.data; alert(message)//判断秒杀是否成功、自行处理逻辑 }; } } 客户端API 客户端与服务器通信 send() 向远程服务器发送数据 close() 关闭该websocket链接 监听函数 onopen 当网络连接建立时触发该事件 onerror 当网络发生错误时触发该事件 onclose 当websocket被关闭时触发该事件 onmessage 当websocket接收到服务器发来的消息的时触发的事件,也是通信中最重要的一个监听事件。msg.data readyState属性 这个属性可以返回websocket所处的状态。 CONNECTING(0) websocket正尝试与服务器建立连接 OPEN(1) websocket与服务器已经建立连接 CLOSING(2) websocket正在关闭与服务器的连接 CLOSED(3) websocket已经关闭了与服务器的连接 开源方案 goeasy GoEasy实时Web推送,支持后台推送和前台推送两种:后台推送可以选择Java SDK、 Restful API支持所有开发语言;前台推送:JS推送。无论选择哪种方式推送代码都十分简单(10分钟可搞定)。由于它支持websocket 和polling两种连接方式所以兼顾大多数主流浏览器,低版本的IE浏览器也是支持的。 地址:http://goeasy.io/ Pushlets Pushlets 是通过长连接方式实现“推”消息的。推送模式分为:Poll(轮询)、Pull(拉)。 地址:http://www.pushlets.com/ Pushlet Pushlet 是一个开源的 Comet 框架,Pushlet 使用了观察者模型:客户端发送请求,订阅感兴趣的事件;服务器端为每个客户端分配一个会话 ID 作为标记,事件源会把新产生的事件以多播的方式发送到订阅者的事件队列里。 地址:https://github.com/wjw465150/Pushlet 总结 其实前面有提过,尽管WebSocket有诸多优点,但是,如果服务端维护很多长连接也是挺耗费资源的,服务器集群以及览器或者客户端兼容性问题,也会带来了一些不确定性因素。大体了解了一下各大厂的做法,大多数都还是基于轮询的方式实现的,比如:腾讯PC端微信扫码登录、京东商城支付成功通知等等。 有些小伙伴可能会问了,轮询岂不是会更耗费资源?其实在我看来,有些轮询是不可能穿透到后端数据库查询服务的,比如秒杀,一个缓存标记位就可以判定是否秒杀成功。相对于WS的长连接以及其不确定因素,在秒杀场景下,轮询还是相对比较合适的。 思考 最后,思考一个问题:100件商品,假如有一万人进行抢购,该如何设置队列长度? 秒杀案例:https://gitee.com/52itstyle/spring-boot-seckill 参考 https://blog.52itstyle.com/archives/736/ https://www.xoriant.com/blog/mobility/websocket-web-stateful-now.html

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

Java高并发秒杀业务Api-Service层构建过程

章节目录 秒杀Service 接口开发工作 秒杀业务逻辑编写 spring-IOC 管理 service 组件 context:component-scan Spring 声明式事务 junit测试 创建基本的代码包层 1.创建DTO - 数据传输层对象 网络数据到达Controller 层后会使用框架自带的数据绑定 以及反序列化为dto对 象,并作为参数传递至service层进行处理。 2.业务接口实现 注意:业务接口的实现需要站在使用者的角度去设计接口 方法定义粒度-非常明确,参数简练,直接,不要一个大map对象去传递,return 还可以抛出异常。 代码如下:业务逻辑接口声明类 SecKillService.java package org.seckill.service; import org.seckill.domain.SecKill; import org.seckill.dto.Exposer; import org.seckill.dto.SecKillExcution; import org.seckill.exception.RepeatKillException; import org.seckill.exception.SecKillCloseException; import org.seckill.exception.SecKillException; import java.util.List; /** * 业务接口的实现需要站在使用者的角度去设计接口 * 三个方面:方法定义粒度、参数、返回类型 dto就可以 */ public interface SecKillService { /** * 返回秒杀商品列表 * * @return */ List<SecKill> getSecKillList(); /** * 查询秒杀商品单条记录 * * @param secKillId * @return */ SecKill getSecKillById(long secKillId); /** * 秒杀开启时,输出秒杀接口的地址,否则输出系统时间,和秒杀时间 * * @param secKillId * @return */ Exposer exportSecKillUrl(long secKillId); /** * 执行秒杀操作 * 验证当前的excuteSecKill id 与 传递过来的md5是否相同 * * @param secKillId * @param userPhone * @param md5 */ SecKillExcution excuteSecKill(long secKillId, String userPhone, String md5) throws SecKillException, RepeatKillException, SecKillCloseException; } 业务逻辑接口实现类-SecKillServiceImpl package org.seckill.service.impl; import org.seckill.dao.SecKillDao; import org.seckill.dao.SuccessKilledDao; import org.seckill.domain.SecKill; import org.seckill.domain.SuccessKilled; import org.seckill.dto.Exposer; import org.seckill.dto.SecKillExcution; import org.seckill.enums.SecKillStateEnum; import org.seckill.exception.RepeatKillException; import org.seckill.exception.SecKillCloseException; import org.seckill.exception.SecKillException; import org.seckill.service.SecKillService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.DigestUtils; import java.util.Date; import java.util.List; @Service public class SecKillServiceImpl implements SecKillService { //在业务逻辑层打日志 private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowire private SecKillDao secKillDao; @Autowire private SuccessKilledDao successKilledDao; //md5加盐,混淆加密 private final String salt = "asdasd8Zy*&ZCY87ywer7t678tzt67wer"; public List<SecKill> getSecKillList() { return secKillDao.queryAll(0, 4); } public SecKill getSecKillById(long secKillId) { return secKillDao.queryById(secKillId); } public Exposer exportSecKillUrl(long secKillId) { SecKill secKill = secKillDao.queryById(secKillId); if (secKill == null) { return new Exposer(false, secKillId);//没有相关产品的秒杀活动 } Date startTime = secKill.getStartTime(); Date endTime = secKill.getEndTime(); Date nowTime = new Date(); if (nowTime.getTime() < startTime.getTime() || nowTime.getTime() > endTime.getTime()) { return new Exposer(false, secKillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());//没有相关产品的秒杀活动 } //转化特定字符串的过程,不可逆 String md5 = null; return new Exposer(secKillId, md5, true); } /** * 生成对应秒杀商品的md5值,做参数校验 * 保证可重用 * * @param secKillId * @return */ private String getMD5(long secKillId) { String base = secKillId + "/" + salt;//用户不知道salt String md5 = DigestUtils.md5DigestAsHex(base.getBytes()); return md5; } /** * 执行秒杀 * * @param secKillId * @param userPhone * @param md5 * @return * @throws SecKillException * @throws RepeatKillException * @throws SecKillCloseException */ public SecKillExcution excuteSecKill(long secKillId, String userPhone, String md5) throws SecKillException, RepeatKillException, SecKillCloseException { try { //1.用户输入的md5值验证 if (md5 == null || !md5.equals(getMD5(secKillId))) { throw new SecKillException("seckill data rewrite"); } //2.减库存、执行秒杀逻辑+记录购买行为,执行秒杀时间 Date nowTime = new Date(); int updateCount = secKillDao.reduceStock(secKillId, nowTime); if (updateCount <= 0) { //没有更新到记录,秒杀结束 throw new SecKillCloseException("seckill is closed"); } else { //3.记录购买行为 insertSuccessKilled 可能出现数据库连接超时等问题,所以需要外层try int insertCount = successKilledDao.insertSuccessKilled(secKillId, userPhone); //唯一验证,secKillId + userPhone if (insertCount <= 0) {//数据库联合主键冲突 throw new RepeatKillException("seckill repeated"); } else {//秒杀成功,返回秒杀成功的实体 SuccessKilled successKilled = successKilledDao.queryByIdWithSecKill(secKillId, userPhone); //不优雅的实现方式,在多处需要用到提示信息时,我们可以采用统一的常量去返回,这样待客户端提示语改变时,我们可以统一进行更改。 // return new SecKillExcution(secKillId, 1, "秒杀成功", successKilled); return new SecKillExcution(secKillId, SecKillStateEnum.SUCCESS, successKilled); } } } catch (SecKillCloseException e1) { throw e1;//还是要回滚 } catch (RepeatKillException e2) { throw e2;//还是要回滚 } catch (Exception e) { logger.error(e.getMessage()); //所有异常最终会转化为 运行时异常,spring 的声明式事务会帮我们做rollback。 throw new SecKillException("seckill inner error" + e.getMessage()); } } } 数据传输层类- Exposer package org.seckill.dto; /** * 暴露秒杀接口 */ public class Exposer { private boolean exposed;//秒杀是否开启标志位 private String md5; //加密措施,暴露地址包括一个md5值 private long now; //系统当前时间(毫秒),方便浏览器计算距离服务器秒杀开启时间 private long secKillId; //秒杀商品的id private long start; private long end; //秒杀正在进行 public Exposer(long secKillId, String md5, boolean exposed) { this.secKillId = secKillId; this.md5 = md5; this.exposed = exposed; } //秒杀结束或还没开启 public Exposer(boolean exposed, long secKillId, long now, long start, long end) { this.exposed = exposed; this.secKillId = secKillId; this.now = now; this.start = start; this.end = end; } //没有相关商品秒杀活动 public Exposer(boolean exposed, long secKillId) { this.exposed = exposed; this.secKillId = secKillId; } public boolean isExposed() { return exposed; } public void setExposed(boolean exposed) { this.exposed = exposed; } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } public long getNow() { return now; } public void setNow(long now) { this.now = now; } public long getStart() { return start; } public void setStart(long start) { this.start = start; } public long getEnd() { return end; } public void setEnd(long end) { this.end = end; } public long getSecKillId() { return secKillId; } public void setSecKillId(long secKillId) { this.secKillId = secKillId; } @Override public String toString() { return "Exposer{" + "exposed=" + exposed + ", md5='" + md5 + '\'' + ", now=" + now + ", secKillId=" + secKillId + ", start=" + start + ", end=" + end + '}'; } } 数据传输层-SecKillExcution package org.seckill.dto; import org.seckill.domain.SuccessKilled; import org.seckill.enums.SecKillStateEnum; /** * 执行秒杀之后的结果 */ public class SecKillExcution { private long secKillId; private int state;//状态的标识 private String stateInfo;//状态表示 private SuccessKilled successSecKilled;//秒杀成功对象 //成功 jakson 在转化枚举的时候会出现问题,不支持枚举序列化 public SecKillExcution(long secKillId, SecKillStateEnum secKillStateEnum, SuccessKilled successSecKilled) { this.secKillId = secKillId; this.state = secKillStateEnum.getState(); this.stateInfo = secKillStateEnum.getStateInfo(); this.successSecKilled = successSecKilled; } //失败,使用到枚举 public SecKillExcution(long secKillId, SecKillStateEnum secKillStateEnum) { this.secKillId = secKillId; this.state = secKillStateEnum.getState(); this.stateInfo = secKillStateEnum.getStateInfo(); } public long getSecKillId() { return secKillId; } public void setSecKillId(long secKillId) { this.secKillId = secKillId; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getStateInfo() { return stateInfo; } public void setStateInfo(String stateInfo) { this.stateInfo = stateInfo; } public SuccessKilled getSuccessSecKilled() { return successSecKilled; } public void setSuccessSecKilled(SuccessKilled successSecKilled) { this.successSecKilled = successSecKilled; } @Override public String toString() { return "SecKillExcution{" + "secKillId=" + secKillId + ", state=" + state + ", stateInfo='" + stateInfo + '\'' + ", successSecKilled=" + successSecKilled + '}'; } } 业务运行时异常类-SecKillException、RepeatKillException、SecKillCloseException package org.seckill.exception; /** * 秒杀相关业务异常 */ public class SecKillException extends RuntimeException { public SecKillException(String message) { super(message); } public SecKillException(String message, Throwable cause) { super(message, cause); } } package org.seckill.exception; /** * 重复秒杀的异常(运行时异常) * 声明式事务,只接收运行时异常 */ public class RepeatKillException extends SecKillException { public RepeatKillException(String message) { super(message); } public RepeatKillException(String message, Throwable cause) { super(message, cause); } } package org.seckill.exception; /** * 秒杀关闭异常-友好响应给用户 */ public class SecKillCloseException extends SecKillException { public SecKillCloseException(String message) { super(message); } public SecKillCloseException(String message, Throwable cause) { super(message, cause); } } 2.spring-IOC管理 service 组件 spring-service.xml 配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描service包下所有使用注解的类型--> <context:component-scan base-package="org.seckill.service" /> <!-- 配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库连接池--> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置基于注解的声明式事务 默认使用注解来管理事务行为 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans> Spring 声明式事务 什么是声明式事务 声明式事务 底层原理:采用动态代理的方式为我们的事务核心逻辑添加开启事务、回滚提交事务的控制操作 声明式事务使用方式 声明式事务 推荐使用@Transactional 声明式事务的传播行为 定义:即事务方法的嵌套 一个业务需要调用多个声明了事务控制的方法,那么最新组合的事务是重新启动一个事务,还是说沿用老的事务呢? 默认的事务传播行为: propagation_required 浅析如下: ServiceA { void methodA() { ServiceB.methodB(); } } ServiceB { void methodB() { } } 比如说ServiceB.methodB 事务传播行为定义为PROPAGATION_REQUIRED, 那么当ServiceA.methodA 调用 ServiceB.methodB 时,methodA起了新的事 务,那么ServiceB.methodB看到自己已经运行在ServiceA.methodA的事务内 部,就不再起新的事务。 而假如ServiceA.methodA运行的时候发现自己没有在事务中,他就会为自己 分配一个事务。这样,在ServiceA.methodA或者在ServiceB.methodB内的任何 地方出现异常,事务都会被回滚。即使ServiceB.methodB的事务已经被提交, 但是ServiceA.methodA在接下来fail要回滚,ServiceB.methodB也要回滚 相当于 methodB 通过自己的事务传播行为告诉methodA 自己使用事务的原 则,告诉methodA 你要有事务我methodB就用你的,如果methodA没有事务, 那你methodA就需要创建一个事务。 什么时候回滚事务 当业务方法抛出运行时异常(RuntimeException)的时候spring 事务管理器会进行commit 配置事务管理器 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"> </bean> 配置基于注解的声明式事务 <tx:annotation-driven transaction-manager="transactionManager"/> 使用注解控制事务方法的优点 开发团队达成一致约定,约定明确标注事务方法的编程风格 保证事务方法的执行时间尽可能的短,不要穿插其他的网络操作,RPC/HTTP请求,如果必须需要的话,那么将这些请求剥离出来,形成一个干净的方法调用。不要混合编写和外部系统进行网络通信的代码。 不是所有的方法都需要事务,select、insert操作,单条语句的insert、update都不需要事务操作、不需要并发控制&多个操作联合形成一个事务时,不需要设置事务,因为mysql有autocommit=1的设置。 上述是性能杀手啊 ,注意再注意。 单元测试 package org.seckill.service; import org.junit.Test; import org.junit.runner.RunWith; import org.seckill.domain.SecKill; import org.seckill.dto.Exposer; import org.seckill.dto.SecKillExcution; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring/spring-dao.xml", "classpath:spring/spring-service.xml"}) public class SecKillServiceTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private SecKillService secKillService; @Test public void getSecKillList() throws Exception { List<SecKill> secKillList = secKillService.getSecKillList(); logger.info("list{}", secKillList); } @Test public void getSecKillById() throws Exception { long secKillId = 1000L; SecKill secKill = secKillService.getSecKillById(secKillId); logger.info("seckill{}", secKill); } @Test public void exportSecKillUrl() throws Exception { long secKillId = 1000L; Exposer exposer = secKillService.exportSecKillUrl(secKillId); logger.info("exposer{}", exposer); } @Test public void excuteSecKill() throws Exception { long secKillId = 1000L; String userPhone = "15300815981"; String md5 = "6e3cc65f3b42e656bdbc55a6a381f5d0"; SecKillExcution secKillExcution = secKillService.excuteSecKill(secKillId, userPhone, md5); logger.info("secKillExcution{}", secKillExcution); } } intellj idea 下单元测试快捷键:ctrl+shift+t

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

基于Java语言构建区块链(二)—— 工作量证明

最终内容请以原文为准:https://wangwei.one/posts/7890ab7e.html 引言 在上一篇文章中,我们实现了区块链最基本的数据结构模型,添加区块以及和前一个区块连接在一起。但是,我们的实现方式非常简单,而真实的比特币区块链中,每一个区块的添加都是需要经过大量的计算才可以完成,这个过程就是我们熟知的挖矿。 工作量证明机制 区块链最关键的一个思想就是,必须进行大量且困难的计算工作才能将交易数据存放到区块链上。这种工作机制才能保证整个区块链数据的安全性和一致性。同时,完成这个计算工作的矿工会得到相应的Token奖励。 这套机制和我们的现实生活非常相似:我们必须努力工作来赚取报酬用以维持我们的生活。在区块链中,网络中的矿工们努力工作来维持区块链网络,为其添加区块,并且获得一定的Token奖励。作为他们工作的成果,一个区块以安全的方式被组合进了区块链中,这样就保证了整个区块链数据库的稳定性。还有一个必须要注意的是,某个矿工完成了计算工作的结果,还必须得到其他所有矿工的认同(证明是正确的),这样才算完成。 这一整套的计算和证明机制,就称为Proof-of-Work(工作量证明)。计算工作是非常非常困难的,因为它需要消耗大量的计算机算力资源,即使是性能非常高的计算机都不能非常快地计算出正确的结果。此外,随着时间的推移,这项计算工作的难度也会随之增加,目的是为了保证每小时6个新区块的出块率。在比特币中,这种工作的目标是找到满足某个特定要求的区块Hash(哈希值)。这个区块哈希值就是工作结果的一个证明。因此,计算工作的目的就是为了寻找到这个证明值。 最后要注意的是,计算出这个特定的Hash(哈希值)是非常困难的,但是别人来验证这个Hash值是否正确的时候,是非常简单的,一下子就能完成。 Hashing Hash:哈希 | 散列 我们来讨论一下Hashing(哈希),对这一块非常熟悉的朋友可以直接跳过这一段内容。 哈希是一种计算机算法,该算法能够计算出任意大小数据的哈希值,并且这个哈希值的长度是固定的,256bit。这个被计算出来的哈希值能够作为这个数据的唯一代表。哈希算法有几个关键的特性: 不可逆性。不能根据一个哈希值推导出原始数据。所以,哈希不是加密。 唯一性。每个数据有且仅有一个唯一的哈希值。 迥异性。原始数据一丁点的变化都将得到完全不一样的哈希值。 例如: SHA256("wangwei1") ——> 1e898b7c9adaad86c20139a302ccd5277f81040cab68dc2aecfc684773532652 SHA256("wangwei2") ——> c9cc7417c17318c8aab448cc8ace24c53b6dcf350f5c5fd8e91cbc3b011a179d 哈希算法被广泛用于验证文件的一致性上。比如软件提供商通常会在安装包上附加一个检验码(checksums),当我们下载完一个软件安装包后,可以用哈希函数计算一下这个软件安装包的哈希值,然后再和软件安装包的检验码做个对比,就可以知道下载的安装包是否完整、是否有数据丢失。 在区块链中,哈希值用于保证区块的一致性。每一个区块被用于进行哈希计算的数据,都包含前一个区块链的哈希值,因此任何人想要修改区块的数据几乎是不可能的,他必须要把整个区块链中从创世区块到最新的区块的所有哈希值全部重新计算一遍。 你可以脑补一下这个工作量有多大,按照目前计算机的算力来看,几乎不可能 Hashcash 比特币的工作量证明是使用的是Hashcash算法,一种最初被用于反垃圾邮件的算法,它可以被拆解为以下几步: 获取某种公开可知的数据data(在邮件案例中,指的是收件人邮件地址;比特币案例中,指的是区块头) 添加一个计数器counter,初始值设置为0; 计算 data 与 counter拼接字符串的哈希值; 检查上一步的哈希值是否满足某个条件,满足则停止计算,不满足则 counter 加1,然后重复第3步和第4步,直到满足这个特定的条件为止。 这是一种粗暴的算法:你改变计数器,计算一个新的哈希值,检查它,增加计数器,计算一个新的哈希值,循环往复,这就是为什么它需要花费大量计算机算力资源的原因所在。 让我们来近距离看一下这个特定的条件指的是什么。在原始的Hashcash算法中,这个特殊的要求指的是计算出来的哈希值的前20bit必须全是零, 在比特币种,这种要求哈希值前面有多少个零打头的要求是随着时间的推移而不断调整的,这是出于设计的目的,尽管在计算机的算力会不断的提升和越来越多的矿工加入这个网络中的情况下,都要保证每10min生产一个区块。 我们演示一下这个算法, # 计算字符串'I like donuts'的哈希值 SHA256("I like donuts") ——> f80867f6efd4484c23b0e7184e53fe4af6ab49b97f5293fcd50d5b2bfa73a4d0 # 拼接一个计数器值(ca07ca),再次进行Hash计算 SHA256("I like donutsca07ca") ——> 0000002f7c1fe31cb82acdc082cfec47620b7e4ab94f2bf9e096c436fc8cee06 这里的ca07ca是计数器值的十六进制,他表示的十进制值为13240266 即,从0开始,总共计算了13240266次,才计算出I like donuts这个数据的Hash值,满足前6位(3字节)全是零。 代码实现 思路: 1)每次区块被添加到区块链之前,先要进行挖矿(Pow) 2)挖矿过程中,产生的 Hash 值,如果小于难度目标值则添加进区块,否则继续挖矿,直到找到正确的Hash为止 3)最后,验证区块Hash是否有效 定义Pow类 /** * 工作量证明 * * @author wangwei * @date 2018/02/04 */ @Data public class ProofOfWork { /** * 难度目标位 */ public static final int TARGET_BITS = 20; /** * 区块 */ private Block block; /** * 难度目标值 */ private BigInteger target; private ProofOfWork(Block block, BigInteger target) { this.block = block; this.target = target; } /** * 创建新的工作量证明,设定难度目标值 * <p> * 对1进行移位运算,将1向左移动 (256 - TARGET_BITS) 位,得到我们的难度目标值 * * @param block * @return */ public static ProofOfWork newProofOfWork(Block block) { BigInteger targetValue = BigInteger.valueOf(1).shiftLeft((256 - TARGET_BITS)); return new ProofOfWork(block, targetValue); } } 设定一个难度目标位TARGET_BITS,表示最终挖矿挖出来Hash值,转化为二进制后,与256相比,长度少了多少bit,也即二进制前面有多少bit是零. TARGET_BITS 越大,最终targetValue就越小,要求计算出来的Hash越来越小,也就是挖矿的难度越来越大。 我们这里的TARGET_BITS是固定的,但是在真实的比特币中,难度目标是随着时间的推推,会动态调整的。详见:《精通比特币 (第二版)》第10章 由于数值比较大,这里要使用BitInteger类型。 准备数据 /** * 准备数据 * <p> * 注意:在准备区块数据时,一定要从原始数据类型转化为byte[],不能直接从字符串进行转换 * @param nonce * @return */ private String prepareData(long nonce) { byte[] prevBlockHashBytes = {}; if (StringUtils.isNoneBlank(this.getBlock().getPrevBlockHash())) { prevBlockHashBytes = new BigInteger(this.getBlock().getPrevBlockHash(), 16).toByteArray(); } return ByteUtils.merge( prevBlockHashBytes, this.getBlock().getData().getBytes(), ByteUtils.toBytes(this.getBlock().getTimeStamp()), ByteUtils.toBytes(TARGET_BITS), ByteUtils.toBytes(nonce) ); } 参与Hash运算的如下几个信息: 前一个区块(父区块)的Hash值; 区块中的交易数据; 区块生成的时间; 难度目标; 用于工作量证明算法的计数器 详见:《精通比特币 (第二版)》第09章 Pow算法 /** * 运行工作量证明,开始挖矿,找到小于难度目标值的Hash * * @return */ public PowResult run() { long nonce = 0; String shaHex = ""; System.out.printf("Mining the block containing:%s \n", this.getBlock().getData()); long startTime = System.currentTimeMillis(); while (nonce < Long.MAX_VALUE) { String data = this.prepareData(nonce); shaHex = DigestUtils.sha256Hex(data); if (new BigInteger(shaHex, 16).compareTo(this.target) == -1) { System.out.printf("Elapsed Time: %s seconds \n", (float) (System.currentTimeMillis() - startTime) / 1000); System.out.printf("correct hash Hex: %s \n\n", shaHex); break; } else { nonce++; } } return new PowResult(nonce, shaHex); } 循环体里面主要以下四步: 准备数据 进行sha256运算 转化为BigInter类型 与target进行比较 最后,返回正确的Hash值以及运算计数器nonce 验证区块Hash有效性 /** * 验证区块是否有效 * * @return */ public boolean validate() { String data = this.prepareData(this.getBlock().getNonce()); return new BigInteger(DigestUtils.sha256Hex(data), 16).compareTo(this.target) == -1; } 修改区块添加逻辑 /** * <p> 创建新区块 </p> * * @param previousHash * @param data * @return */ public static Block newBlock(String previousHash, String data) { Block block = new Block("", previousHash, data, Instant.now().getEpochSecond(), 0); ProofOfWork pow = ProofOfWork.newProofOfWork(block); PowResult powResult = pow.run(); block.setHash(powResult.getHash()); block.setNonce(powResult.getNonce()); return block; } 创建区块 创建Pow算法对象 执行Pow算法 保存返回的Hash以及运算计数器 测试运行 /** * 测试 * * @author wangwei * @date 2018/02/05 */ public class BlockchainTest { public static void main(String[] args) { Blockchain blockchain = Blockchain.newBlockchain(); blockchain.addBlock("Send 1 BTC to Ivan"); blockchain.addBlock("Send 2 more BTC to Ivan"); for (Block block : blockchain.getBlockList()) { System.out.println("Prev.hash: " + block.getPrevBlockHash()); System.out.println("Data: " + block.getData()); System.out.println("Hash: " + block.getHash()); System.out.println("Nonce: " + block.getNonce()); ProofOfWork pow = ProofOfWork.newProofOfWork(block); System.out.println("Pow valid: " + pow.validate() + "\n"); } } } /** * 设定TARGET_BITS = 20,得到如下结果: */ Mining the block containing:Genesis Block Elapsed Time: 2.118 seconds correct hash Hex: 00000828ee8289ef6381f297585ef8c952fde93fc2b673ff7cc655f699bb2442 Mining the block containing:Send 1 BTC to Ivan Elapsed Time: 1.069 seconds correct hash Hex: 00000a38c0d7f2ebbd20773e93770298aa8bc0cc6d85fca8756fe0646ae7fea5 Mining the block containing:Send 2 more BTC to Ivan Elapsed Time: 4.258 seconds correct hash Hex: 00000777f93efe91d9aabcba14ab3d8ab8e0255b89818cdb9b93cfa844ad0c7f Prev.hash: Data: Genesis Block Hash: 00000828ee8289ef6381f297585ef8c952fde93fc2b673ff7cc655f699bb2442 Nonce: 522163 Pow valid: true Prev.hash: 00000828ee8289ef6381f297585ef8c952fde93fc2b673ff7cc655f699bb2442 Data: Send 1 BTC to Ivan Hash: 00000a38c0d7f2ebbd20773e93770298aa8bc0cc6d85fca8756fe0646ae7fea5 Nonce: 474758 Pow valid: true Prev.hash: 00000a38c0d7f2ebbd20773e93770298aa8bc0cc6d85fca8756fe0646ae7fea5 Data: Send 2 more BTC to Ivan Hash: 00000777f93efe91d9aabcba14ab3d8ab8e0255b89818cdb9b93cfa844ad0c7f Nonce: 1853839 Pow valid: true 总结 我们正在一步一步接近真实的区块链架构,本篇我们实现了挖矿机制,但是我们还有很多关键性的功能没有实现:区块链数据库的持久性、钱包、地址、交易、共识机制,这些我们后面一步一步来实现 资料 源代码:https://github.com/wangweiX/blockchain-java/tree/part2-pow https://jeiwan.cc/posts/building-blockchain-in-go-part-2/ 《精通比特币(第二版)》

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

腾讯云软件源

腾讯云软件源

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

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

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

用户登录
用户注册
修改密码
忘记密码