首页 文章 精选 留言 我的

精选列表

搜索[Transformer架构],共10005篇文章
优秀的个人博客,低调大师

LNMP架构介绍

和LAMP不同的是,提供web服务的是Nginx 并且php是作为一个独立服务存在的,这个服务叫做php-fpm Nginx直接处理静态请求,动态请求会转发给php-fpm 原理是:lnmp里的php会启动一个服务,nginx把用户请求的php交给php-fpm处理,比如登录网站php要和mysql做交互,查用户的账号和密码,处理完之后,php-fpm会告诉nginx,nginx返回给用户一个结果。Nginx对于一些静态请求就自己处理了,不需要交给php处理。 本文转自 虾米的春天 51CTO博客,原文链接:http://blog.51cto.com/lsxme/2056606,如需转载请自行联系原作者

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

MyBatis整体架构

一、模块概览 模块名称 作用 主要类 反射模块 封装JAVA API,易用,进行了缓存优化 类型转换模块 绑定实参及映射查询结果集 日志模块 定位BUG,解决瓶颈 资源加载模块 类加载器,确定类加载器使用顺序 解析器模块 Xpath,初始化解析mybatis-confg.xml,mapper.xml, 动态SQL占位符 XPathParser TokenHandler EntityResolver 数据源模块 事务管理模块 抽象处理 缓存模块 提供一级和二级缓存 Binding模块 自定义Mapper接口与映射语句关联 二、模块分析 2.1 解析器模块 顾名思义:提供XML文件的解析。 GenericTokenParser:通用的占位符解析器。 TokenHandler:解析占位符 2.2 反射工具箱 Reflector:一个Reflector对应一个类,缓存了反射需要类的元信息。 ReflectorFactory:生成缓存Reflector TypeParameterResolver:工具类,解析指定类中的字段,方法返回值,方法参数的类型。 PropertyTokenizer 是一个Iterator接口,实现嵌套属性解析。 MetaClass:类级别元信息的封装和处理 ObjectWrapper:对象的包装,抽象了对象的属性信息,定义了更新属性,查询属性信息的方法。 ObjectFactory:创建指定类型的对象 MetaObject:调用ObjectWrapper,完成对象属性的检测,获取,设置等功能。 3. 类型转换 JDBC到JAVA类型转换 及JAVA类型到JDBC类型转换,两种不同类型的桥梁。 ResolverUtil:根据指定的条件查找指定包下的类。 3.日志模块 适配了第三方日志接口的差异。 JDBC调试:通过JDK动态代理方式,将JDBC操作通过指定的日志框架打印出来。 4.Binding MapperProxy:代理对象 MapperRegistry:Mapper接口及对应代理对象工厂的注册中心。 MapperMethod:封装了Mapper接口中对应方法的信息,以及SQL语句信息。 ParamNameResolver:Mapper接口定义的方法参数。记录参数列表中位置索引和参数名称对应关系 MethodSignature:Mapper接口中定义的方法的相关信息。 本文转自 randy_shandong 51CTO博客,原文链接:http://blog.51cto.com/dba10g/1966021,如需转载请自行联系原作者

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

ADFS 架构介绍

ADFS可以作为单台服务器存在,也可以作为群集存在。 在一个域中,可以存在多台独立的adfs,并且他们相互不干扰也不存在任何关系。也就是说允许存在多个adfs系统,用于提供给不同服务。例如y.com中可以存在一台adfs.y.com的联合身份验证服务器和存在一台sso.y.com的联合身份验证服务器,这两台服务器彼此独立。 另外一种情况就是adfs的群集,这分两种情况, 一种是使用windows内置数据库, 一种是使用sql数据库。 区别在于,使用windows内置数据库的adfs有一台主服务器,其他是从属服务器,其中主服务器可以写入adfs数据库,而其他从服务器只能提供adfs的验证,数据库可读,但是不可写入。也可以正常提供adfs服务,但是要进行系统配置的时候只能配置主服务器,如添加一个信赖方配置,从服务器无法配置。 而使用sql数据库,不存在从属关系,任意一台ADFS服务器都可以配置,并且会自动同步到所有服务器 下面找到一篇文章介绍,转载自:http://www.myexception.cn/dynamics-crm/2155784.html 默认拓扑Active Directory联合身份验证服务(AD FS)是联合服务器场,使用Windows内部数据库(WID)。 在这种拓扑,AD FS使用WID作为存储的所有联合服务器加入到该场的AD FS配置数据库。 服务器场复制和维护场中每台服务器的配置数据库中的联合身份验证服务数据。AD FS Windows Server 2012 R2中启用具有100个或更少信赖方信任配置使用最多30个服务器使用WID的联合服务器场的组织。 创建第一个联合服务器场中的操作也将创建新的联合身份验证服务。当您使用WID的AD FS配置数据库时,在服务器场中创建的第一个联合服务器称为主联合服务器。这意味着此计算机配置AD FS配置数据库的读/写副本。 为此服务器场配置的所有其他联合服务器称为辅助联合服务器因为它们必须将复制到它们在本地存储的AD FS配置数据库的只读副本的主联合服务器所做的任何更改。 下表提供有关使用WID服务器场的摘要。 使用它来计划您的实现。 1-100 RP 信任 超过 100 个 RP 信任 1-30 AD FS 节点 WID 支持 使用 WID 的所需 SQL 不支持 超过 30 AD FS 节点 使用 WID 的所需 SQL 不支持 使用 WID 的所需 SQL 不支持 此拓扑图的优缺点: 1、WID是随Windows;因此,无需购买SQL Server 2、提供对内部用户的SSO访问 拓扑图: 注意: 如果在此单个NLB 主机上出现故障,用户不能访问联合应用程序或服务。 如果您的业务要求不允许存在单点故障,请添加其他 NLB 主机。 本文转自 流原炫 51CTO博客,原文链接:http://blog.51cto.com/xiaoyuanzheng/1964280

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

BMC测试架构

A Test Framework of BMC for platform team Table of Contents A Test Framework of BMC for platform team.. 1 Introduction. 1 Requirement Analyze. 2 General Design. 2 Requirement. 2 Not requirement:3 Model Design. 3 Pre-run model3 Functional model3 IPMI device “Global” Commands. 3 BMC Watchdog Timer Commands. 4 Chassis Commands. 4 Event commands. 5 PEF and Alerting command. 5 SEL commands. 5 SDR Repository command. 5 FRU Inventory Device Commands. 6 Event Filter Table. 6 Sensor Device commands. 6 Platform-specific OEM command. 7 Post-run model7 Implement. 7 Requirement. 7 User interface. 7 Schedule. 7 Introduction As theone most important component of a server, BMC is used to monitor system environmentmonitoring, hardware error and record related logs, so its high availabilityand stability is critical to us. Currently platform always use some manualscripts or commands to do BMC test, in fact the scripts and commands can be puttogether and re-used for other platform, and we can leverage other team’s testframework such as CTH test platform to test it automatically, therefore oneTest Frame work for BMC test is need, and this document is used to describe thedesign of the framework. RequirementAnalyze Typically uses cases include: 1.OEM SEL decodingTest for customer ipmitool/unit test 2.BMC stress test 3.BMC function test 4.BMC regression test 5.System monitro 6.Platform monitor 7.Firmware upgrade 8.Netmon GeneralDesign Requirement ·support both local KCS test and LAN test ·Could be integrate with EVT test framework ·Could be integrated with CTH test tools oGraphic user interface; oSupport auto Log; oSupport automatically report; oTests mode/collection configurable; ·To be easily expanded for new platform; ·To be easily expanded for other component This requires that other software component own by platform team such asplatmon/error handling will be easily tested by this framework. ·Support auto-training; That means the framework will record the test cases which once detectFW/Software problem, and will automatically add them into test case for latertests.Accordingto experience, because we always meet problem when run BMC reset, firmwareupgrade , sensor reading and power cycle test, these type commands should becollected by auto-training mechanism. ·Support multiply test modes: function test;random test; stress test oFunction test:test for every component/unit one by one; oRandom test: the random test generator willproduce the random test cases, such as random raw data, random SELs to BMC oStress test: a.Component level stress test: Many commands run together on the same component such as SEL / SDR / FRU/ Watchdog / CPLD at the same time toverify its availability. b.System level stress test: Many components ran stress test at the same time ·Support an interface to add platform-specifictest; ·The framework makes full use of code withcurrent DDOS The customer ipmitool is implemented in our DDOS according coming BMCspecification, so maybe we could reuse the code and test scripts ·The framework should define test level/log level The test level is used to define the test granularity (sensor level,component level, bus level, function level, chip level) while the log levelhelp debug and log more details about the execution and output of the testcases. ·Base on small generic test sets To start this work easily, we willchoose a basic test cases collection maybe included by all platform, such asBMC SEL, user , SDR, reset, Lan, Fan, FRU and power control command. Not requirement: ·Test for some OEM command which must operatehardware manually; ·Test for whose result may need manuallyinvestigation. ModelDesign Pre-run model Check BMC version requirement; Check BIOS version requirement; check extra parameters; check BMC is in normal state; save BMC IPMIuser/sol/serial/channel/mac/DHCP/IP default configuration; stop system and platform monitro; Functional Test IPMI device “Global” Commands ·Get Device ID command ·Warm Reset command ·Cold Reset command ·Get Self Tests Results command ·Manufacturing Test on command ·Set ACPI power state command ·Get ACPI power state command ·Get Device GUID command ·Broadcast “Get Device ID” command ·Firmware Firewall & Command Discoverycommands ·IPMI Messaging Support Commands oSet BMC Global Enables oGet BMC Global Enables oClear Message Flags oGet Message Flags oGet Message oSend message §Get BT interface Capabilities §Master write-read §IPMI serial/Modem Commands §Set Serial/Modem Configuration §Get Serial/Modemconfiguration §Serial / Modem connection Activ §SOL command ( Optional) §SOL Activating §Get SOL configuration Parameters §Set SOL configuration Parameters PEF and Alerting command Get PEF Capabilities Arm PEF Postpone Timer Set PEF Configuration Parameters Get PEF Configuration Parameters Set Last Processor Event ID Get Last Processor Event ID BMC Watchdog Timer Commands Reset watchdog timer Set Watchdog timer Get Watchdog timer (On expiration of the Watchdog timeout: vSystem Reset vSystem Power Off vSystem power cycle vPre-timeout interrupt (Optional) Chassis Commands Get Chassis capabilities Get Chassis Status Chassis control Chassis Reset Event commands Set event receiver Get event receiver Platform event message command SEL component Trigger all possible SELs in scripts; Delete SELS; Full SELs; Empty SELs; Get SEL Info Get SEL Entry Add SEL Entry Partial Add SEL entry Clear SEL Get SEL time Set SEL time OEM SEL decoding test (How to do the test with our OEM SELsdecoding code?) SDR Repository command Get SDR Repository Info Reserve SDR Repository Get SDR Add SDR Partial Add SDR Clear SDR Repository Get SDR Repository Time Set SDR Repository Time FRU Inventory Device Commands Get Device ID Get Self Test Results Broadcast Get Device ID Get Sensor Reading Set Event Receiver Get Event Receiver Platform Event Event Filter Table Get EFT list Check whether EFT works How to do PEF auto test? Sensor Device commands Static and Dynamic Senor Devices Get Device SDR info commands Get Device SDR command Reserve Devices SDR Repositorycommand Get sensor Reading Factors command Set sensor Hysteresis command Get sensor Hysteresis command Set Sensor Threshold command Get sensors event Enable command Set sensors event disabled command Re-arm sensor Events command User controlling command Lan command Platform-specific OEM command OEM SELs; OEM SLIC command; OEM NVRAM/BBU command (How to classified different OEM commands per platforms?) Random Test Using “ipmitoolevent” command to cover all OEM SEL decoding, this is easy to be done by ascript: Step 1: get allsensors; Step 2: for everysensor, list all possible state Step 3:Assert/Deassert every state Step 4: checkwhether SEL decoding the event correctly. Another method isusing “raw 0x40 0x41” command to emulate all possible SEL, and then using “ipmitoolsel list” to check whether successful to decode them. Stress and Integration Test Power button Test for many times Short presspre-boot Long press pre-boot Short presspost-boot Long presspost-boot Fan controlling Test for manytimes One Fan enterauto-manual control mode Multiply Fancontrolling method switch Sequent Fancontrolling command LED Test for many times Chassis LED Test SP LED Test FAN LED Test SLIC LED Test PSU LED Test Disk LED Test PSU SEL Test Unpowered PSUinserted Powered PSUinserted Unpowered PSU removed powered PSU removed Firmware program Test Firmware versionget Firmware upgrade Firmware downgrade Firmware checksum Firmware otheroption Performance Test Measure keyperformance for most frequent used commands, and compare it with other platform Post-run model check BMC is in normal state; restore BMC IPMI user/sol/serial/FAN/LED/channel/mac/DHCP/IP defaultconfiguration; restore system and platform monitor; Record logs in three different lawer: And then analyze above logs: PASS rate/ FAILrate: ·Command level log: OK/ERROR ·Case level log Component level log; Log upload; Implement Requirement ·Unified final result format: $component test :PASS/FAIL / Unsupported/Not Run ·Easily to expand to new platform for all OEMcommand (Try to reuse all command function in sub script) ·Cover all possible IPMI command maybe used by system daemon process 本文转自存储之厨51CTO博客,原文链接:http://blog.51cto.com/xiamachao/1681454 ,如需转载请自行联系原作者

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

LAMP架构介绍

LAMP是Linux Apache(httpd) MySQL PHP的简写 PHP网站(Google、淘宝、百度、51cto博客) 三个角色可以在一台机器,也可以分开(httpd和PHP要在一起) MySQL是一个关系型数据库,由mysql ab公司开发,mysql在2008年被 sun公司收购,2009年sun公司被oracle公司收购 MySQL官网https://www.mysql.com 最新版本5.7GA/8.0DMR Mariadb为MySQL的一个分支,官网https:mariadb.com/最新版本10.2 MariaDB主要由SkySQL公司(现更名为MariaDB公司)维护,SkySQL公司由MySQL原作者带领原班人马创立 Mariadb5.5版本对应MySQL的5.5,10.0对应MySQL5.6 community 社区版本,enterprise 企业版,GA(Generally Available)指通过版本,在生产环境中用的,DMR(Development Milestone Release)开发里程碑发布版本,RC(Release Candidate)发行候选版本,Beta开放测试版本,Alpha内部测试版本 安装MySQL MySQL的几种常用安装包:rpm(不能指定安装路径)、源码、二进制免编译包(可以指定安装路径) # cd/usr/local/src/ #<==建议以后所有软件包都放在这个目录下面 # uname -i或uname -a #<==查看Linux是多少位 在服务器安装LAMP环境时,wget时提示 -bash:wget command not found ,很明显这是没有安装wget软件包。一般Linux最小化安装时,wget是会默认被安装 解决方法:yum 安装 # yum install -y wget 本文转自 yzllinux博客,原文链接: http://blog.51cto.com/12947851/2073338如需转载请自行联系原作者

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

深入Redux架构

关于redux 之前写了一篇通过一个demo了解Redux,但对于redux的核心方法没有进行深入剖析,在此重新总结学习,完整的代码看这里。(参考了React 技术栈系列教程) 什么情况需要用redux? 用户的使用方式复杂 不同身份的用户有不同的使用方式(比如普通用户和管理员) 多个用户之间可以协作 与服务器大量交互,或者使用了WebSocket View要从多个来源获取数据 简单说,如果你的UI层非常简单,没有很多互动,Redux 就是不必要的,用了反而增加复杂性。多交互、多数据源场景就比较适合使用Redux。 设计思想: Web 应用是一个状态机,视图与状态是一一对应的。 所有的状态,保存在一个对象里面。 Redux工作流程: 首先,用户发出 Action。 store.dispatch(action); 然后,Store 自动调用 Reducer,并且传入两个参数:当前 State 和收到的 Action。 Reducer 会返回新的 State 。 letnextState=todoApp(previousState,action); State 一旦有变化,Store 就会调用监听函数。 //设置监听函数store.subscribe(listener); listener可以通过store.getState()得到当前状态。如果使用的是 React,这时可以触发重新渲染 View。 functionlisterner(){ letnewState=store.getState(); component.setState(newState); } 如果现在没理解以上流程,不要急,看完以下API就差不多能懂得Redux的核心机制了。 回到顶部(go to top) API Store Store 就是保存数据的地方,你可以把它看成一个容器。整个应用只能有一个 Store。 Redux 提供createStore这个函数,用来生成 Store。 下面代码中,createStore函数接受另一个函数作为参数,返回新生成的 Store 对象。 import{createStore}from'redux'; conststore=createStore(fn); State Store对象包含所有数据。如果想得到某个时点的数据,就要对 Store 生成快照。这种时点的数据集合,就叫做 State。 当前时刻的 State,可以通过store.getState()拿到。 import{createStore}from'redux'; conststore=createStore(fn); conststate=store.getState(); Redux 规定, 一个 State 对应一个 View。只要 State 相同,View 就相同。你知道 State,就知道 View 是什么样,反之亦然。 Action State 的变化,会导致 View 的变化。但是,用户接触不到 State,只能接触到 View。所以,State 的变化必须是 View 导致的。Action 就是 View 发出的通知,表示 State 应该要发生变化了。 Action 是一个对象。其中的type属性是必须的,表示 Action 的名称。其他属性可以自由设置,社区有一个规范可以参考。 constaction={ type:'ADD_TODO', payload:'LearnRedux'}; 上面代码中,Action 的名称是ADD_TODO,它携带的信息是字符串Learn Redux。 可以这样理解,Action 描述当前发生的事情。改变 State 的唯一办法,就是使用 Action。它会运送数据到 Store。 Action Creator View 要发送多少种消息,就会有多少种 Action。如果都手写,会很麻烦。可以定义一个函数来生成 Action,这个函数就叫 Action Creator。 constADD_TODO='添加TODO';functionaddTodo(text){return{ type:ADD_TODO, text } } constaction=addTodo('LearnRedux'); store.dispatch() store.dispatch()是 View 发出 Action 的唯一方法。 import{createStore}from'redux'; conststore=createStore(fn); store.dispatch({ type:'ADD_TODO', payload:'LearnRedux'}); 上面代码中,store.dispatch接受一个 Action 对象作为参数,将它发送出去。 结合 Action Creator,这段代码可以改写如下。 store.dispatch(addTodo('LearnRedux')); Reducer Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。 Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。下面是一个实际的例子 constdefaultState=0; constreducer=(state=defaultState,action)=>{switch(action.type){case'ADD':returnstate+action.payload;default: returnstate; } }; conststate=reducer(1,{ type:'ADD', payload:2}); 上面代码中,reducer函数收到名为ADD的 Action 以后,就返回一个新的 State,作为加法的计算结果。其他运算的逻辑(比如减法),也可以根据 Action 的不同来实现。 实际应用中,Reducer 函数不用像上面这样手动调用,store.dispatch方法会触发 Reducer 的自动执行。为此,Store 需要知道 Reducer 函数,做法就是在生成 Store 的时候,将 Reducer 传入createStore方法。 import{createStore}from'redux'; conststore=createStore(reducer); 上面代码中,createStore接受 Reducer 作为参数,生成一个新的 Store。以后每当store.dispatch发送过来一个新的 Action,就会自动调用 Reducer,得到新的 State。 store.subscribe() Store 允许使用store.subscribe方法设置监听函数,一旦 State 发生变化,就自动执行这个函数。 import{createStore}from'redux'; conststore=createStore(reducer); store.subscribe(listener); 显然,只要把 View 的更新函数(对于 React 项目,就是组件的render方法或setState方法)放入listen,就会实现 View 的自动渲染。 store.subscribe方法返回一个函数,调用这个函数就可以解除监听。 letunsubscribe=store.subscribe(()=> console.log(store.getState()) ); unsubscribe(); 回到顶部(go to top) 中间件与异步操作 一个关键问题没有解决:异步操作怎么办?Action 发出以后,Reducer 立即算出 State,这叫做同步;Action 发出以后,过一段时间再执行 Reducer,这就是异步。 怎么才能 Reducer 在异步操作结束后自动执行呢?这就要用到新的工具:中间件(middleware)。 为了理解中间件,让我们站在框架作者的角度思考问题:如果要添加功能,你会在哪个环节添加? (1)Reducer:纯函数,只承担计算 State 的功能,不合适承担其他功能,也承担不了,因为理论上,纯函数不能进行读写操作。 (2)View:与 State 一一对应,可以看作 State 的视觉层,也不合适承担其他功能。 (3)Action:存放数据的对象,即消息的载体,只能被别人操作,自己不能进行任何操作。 想来想去,只有发送 Action 的这个步骤,即store.dispatch()方法,可以添加功能。 中间件的用法 本文不涉及如何编写中间件,因为常用的中间件都有现成的,只要引用别人写好的模块即可。比如,上一节的日志中间件,就有现成的redux-logger模块。这里只介绍怎么使用中间件。 import{applyMiddleware,createStore}from'redux'; importcreateLoggerfrom'redux-logger'; constlogger=createLogger(); conststore=createStore( reducer, applyMiddleware(logger) ); 上面代码中,redux-logger提供一个生成器createLogger,可以生成日志中间件logger。然后,将它放在applyMiddleware方法之中,传入createStore方法,就完成了store.dispatch()的功能增强。 这里有两点需要注意: (1)createStore方法可以接受整个应用的初始状态作为参数,那样的话,applyMiddleware就是第三个参数了。 conststore=createStore( reducer, initial_state, applyMiddleware(logger) ); (2)中间件的次序有讲究。 conststore=createStore( reducer, applyMiddleware(thunk,promise,logger) ); 上面代码中,applyMiddleware方法的三个参数,就是三个中间件。有的中间件有次序要求,使用前要查一下文档。比如,logger就一定要放在最后,否则输出结果会不正确。 回到顶部(go to top) 异步操作的基本思路 理解了中间件以后,就可以处理异步操作了。 同步操作只要发出一种 Action 即可,异步操作的差别是它要发出三种 Action。 操作发起时的 Action 操作成功时的 Action 操作失败时的 Action 以向服务器取出数据为例,三种 Action 可以有两种不同的写法。 //写法一:名称相同,参数不同{type:'FETCH_POSTS'} {type:'FETCH_POSTS',status:'error',error:'Oops'} {type:'FETCH_POSTS',status:'success',response:{...}}//写法二:名称不同{type:'FETCH_POSTS_REQUEST'} {type:'FETCH_POSTS_FAILURE',error:'Oops'} {type:'FETCH_POSTS_SUCCESS',response:{...}} 除了 Action 种类不同,异步操作的 State 也要进行改造,反映不同的操作状态。下面是 State 的一个例子。 letstate={//... isFetching:true, didInvalidate:true, lastUpdated:'xxxxxxx'}; 上面代码中,State 的属性isFetching表示是否在抓取数据。didInvalidate表示数据是否过时,lastUpdated表示上一次更新时间。 现在,整个异步操作的思路就很清楚了。 操作开始时,送出一个 Action,触发 State 更新为"正在操作"状态,View 重新渲染 操作结束后,再送出一个 Action,触发 State 更新为"操作结束"状态,View 再一次重新渲染 redux-thunk中间件 异步操作至少要送出两个 Action:用户触发第一个 Action,这个跟同步操作一样,没有问题;如何才能在操作结束时,系统自动送出第二个 Action 呢? 奥妙就在 Action Creator 之中。 classAsyncAppextendsComponent{ componentDidMount(){ const{dispatch,selectedPost}=this.props dispatch(fetchPosts(selectedPost)) }//... 上面代码是一个异步组件的例子。加载成功后(componentDidMount方法),它送出了(dispatch方法)一个 Action,向服务器要求数据fetchPosts(selectedSubreddit)。这里的fetchPosts就是 Action Creator。 下面就是fetchPosts的代码,关键之处就在里面。 constfetchPosts=postTitle=>(dispatch,getState)=>{ dispatch(requestPosts(postTitle));returnfetch(`/some/API/${postTitle}.json`) .then(response=>response.json()) .then(json=>dispatch(receivePosts(postTitle,json))); }; };//使用方法一store.dispatch(fetchPosts('reactjs'));//使用方法二store.dispatch(fetchPosts('reactjs')).then(()=> console.log(store.getState()) ); 上面代码中,fetchPosts是一个Action Creator(动作生成器),返回一个函数。这个函数执行后,先发出一个Action(requestPosts(postTitle)),然后进行异步操作。拿到结果后,先将结果转成 JSON 格式,然后再发出一个 Action(receivePosts(postTitle, json))。 上面代码中,有几个地方需要注意。 (1)fetchPosts返回了一个函数,而普通的 Action Creator 默认返回一个对象。 (2)返回的函数的参数是dispatch和getState这两个 Redux 方法,普通的 Action Creator 的参数是 Action 的内容。 (3)在返回的函数之中,先发出一个 Action(requestPosts(postTitle)),表示操作开始。 (4)异步操作结束之后,再发出一个 Action(receivePosts(postTitle, json)),表示操作结束。 这样的处理,就解决了自动发送第二个 Action 的问题。但是,又带来了一个新的问题,Action 是由store.dispatch方法发送的。而store.dispatch方法正常情况下,参数只能是对象,不能是函数。 这时,就要使用中间件redux-thunk。 import{createStore,applyMiddleware}from'redux'; importthunkfrom'redux-thunk'; importreducerfrom'./reducers';//Note:thisAPIrequiresredux@>=3.1.0conststore=createStore( reducer, applyMiddleware(thunk) ); 上面代码使用redux-thunk中间件,改造store.dispatch,使得后者可以接受函数作为参数。 因此,异步操作的第一种解决方案就是,写出一个返回函数的 Action Creator,然后使用redux-thunk中间件改造store.dispatch。 回到顶部(go to top) React-Redux的用法 为了方便使用,Redux 的作者封装了一个 React 专用的库React-Redux,本文主要介绍它。 这个库是可以选用的。实际项目中,你应该权衡一下,是直接使用 Redux,还是使用 React-Redux。后者虽然提供了便利,但是需要掌握额外的 API,并且要遵守它的组件拆分规范。 React-Redux 将所有组件分成两大类:UI 组件(presentational component)和容器组件(container component)。 UI组件 UI 组件有以下几个特征。 只负责 UI 的呈现,不带有任何业务逻辑 没有状态(即不使用this.state这个变量) 所有数据都由参数(this.props)提供 不使用任何 Redux 的 API 下面就是一个 UI 组件的例子。 constTitle= value=><h1>{value}</h1>; 因为不含有状态,UI 组件又称为"纯组件",即它纯函数一样,纯粹由参数决定它的值。 容器组件 容器组件的特征恰恰相反。 负责管理数据和业务逻辑,不负责 UI 的呈现 带有内部状态 使用 Redux 的 API 总之,只要记住一句话就可以了:UI 组件负责 UI 的呈现,容器组件负责管理数据和逻辑。 你可能会问,如果一个组件既有 UI 又有业务逻辑,那怎么办?回答是,将它拆分成下面的结构:外面是一个容器组件,里面包了一个UI 组件。前者负责与外部的通信,将数据传给后者,由后者渲染出视图。 React-Redux 规定,所有的 UI 组件都由用户提供,容器组件则是由 React-Redux 自动生成。也就是说,用户负责视觉层,状态管理则是全部交给它。 connect() React-Redux 提供connect方法,用于从 UI 组件生成容器组件。connect的意思,就是将这两种组件连起来。 connect方法的完整 API 如下。 import{connect}from'react-redux'constVisibleTodoList=connect( mapStateToProps, mapDispatchToProps )(TodoList) 上面代码中,TodoList是 UI 组件,VisibleTodoList就是由 React-Redux 通过connect方法自动生成的容器组件。connect方法接受两个参数:mapStateToProps和mapDispatchToProps。它们定义了 UI 组件的业务逻辑。前者负责输入逻辑,即将state映射到 UI 组件的参数(props),后者负责输出逻辑,即将用户对 UI 组件的操作映射成 Action。 mapStateToProps mapStateToProps是一个函数。它的作用就是像它的名字那样,建立一个从(外部的)state对象到(UI 组件的)props对象的映射关系。 作为函数,mapStateToProps执行后应该返回一个对象,里面的每一个键值对就是一个映射。请看下面的例子。 constmapStateToProps=(state)=>{return{ todos:getVisibleTodos(state.todos,state.visibilityFilter) } } 上面代码中,mapStateToProps是一个函数,它接受state作为参数,返回一个对象。这个对象有一个todos属性,代表 UI 组件的同名参数,后面的getVisibleTodos也是一个函数,可以从state算出todos的值。 下面就是getVisibleTodos的一个例子,用来算出todos。 constgetVisibleTodos=(todos,filter)=>{switch(filter){case'SHOW_ALL':returntodoscase'SHOW_COMPLETED':returntodos.filter(t=>t.completed)case'SHOW_ACTIVE':returntodos.filter(t=>!t.completed)default:thrownewError('Unknownfilter:'+filter) } } mapStateToProps会订阅 Store,每当state更新的时候,就会自动执行,重新计算 UI 组件的参数,从而触发 UI 组件的重新渲染。 mapStateToProps的第一个参数总是state对象,还可以使用第二个参数,代表容器组件的props对象。 //容器组件的代码//<FilterLinkfilter="SHOW_ALL">//All//</FilterLink>constmapStateToProps=(state,ownProps)=>{return{ active:ownProps.filter===state.visibilityFilter } } 使用ownProps作为参数后,如果容器组件的参数发生变化,也会引发 UI 组件重新渲染。 connect方法可以省略mapStateToProps参数,那样的话,UI 组件就不会订阅Store,就是说 Store 的更新不会引起 UI 组件的更新。 mapDispatchToProps() mapDispatchToProps是connect函数的第二个参数,用来建立 UI 组件的参数到store.dispatch方法的映射。也就是说,它定义了哪些用户的操作应该当作 Action,传给 Store。它可以是一个函数,也可以是一个对象。 如果mapDispatchToProps是一个函数,会得到dispatch和ownProps(容器组件的props对象)两个参数。 constmapDispatchToProps=( dispatch, ownProps )=>{return{ onClick:()=>{ dispatch({ type:'SET_VISIBILITY_FILTER', filter:ownProps.filter }); } }; } 从上面代码可以看到,mapDispatchToProps作为函数,应该返回一个对象,该对象的每个键值对都是一个映射,定义了 UI 组件的参数怎样发出 Action。 如果mapDispatchToProps是一个对象,它的每个键名也是对应 UI 组件的同名参数,键值应该是一个函数,会被当作 Action creator ,返回的 Action 会由 Redux 自动发出。举例来说,上面的mapDispatchToProps写成对象就是下面这样。 constmapDispatchToProps={ onClick:(filter)=>{ type:'SET_VISIBILITY_FILTER', filter:filter }; } <Provider>组件 connect方法生成容器组件以后,需要让容器组件拿到state对象,才能生成 UI 组件的参数。React-Redux 提供Provider组件,可以让容器组件拿到state。 import{Provider}from'react-redux'import{createStore}from'redux'importtodoAppfrom'./reducers'importAppfrom'./components/App'letstore=createStore(todoApp); render(<Providerstore={store}> <App/> </Provider>, document.getElementById('root') ) 上面代码中,Provider在根组件外面包了一层,这样一来,App的所有子组件就默认都可以拿到state了。 React-Router路由库 使用React-Router的项目,与其他项目没有不同之处,也是使用Provider在Router外面包一层,毕竟Provider的唯一功能就是传入store对象。 constRoot=({store})=>(<Providerstore={store}> <Router> <Routepath="/"component={App}/> </Router> </Provider> ); 本文转自 bxst 51CTO博客,原文链接:http://blog.51cto.com/13013670/1943931

资源下载

更多资源
腾讯云软件源

腾讯云软件源

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

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文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

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

用户登录
用户注册