首页 文章 精选 留言 我的

精选列表

搜索[教程],共9166篇文章
优秀的个人博客,低调大师

GraphQL快速入门教程

摘要: 体验神奇的GraphQL! 原文:GraphQL 入门详解 作者:MudOnTire Fundebug经授权转载,版权归原作者所有。 GraphQL简介 定义 一种用于API调用的数据查询语言 核心思想 传统的api调用一般获取到的是后端组装好的一个完整对象,而前端可能只需要用其中的某些字段,大部分数据的查询和传输工作都浪费了。graphQL提供一种全新数据查询方式,可以只获取需要的数据,使api调用更灵活、高效和低成本。 特点 需要什么就获取什么数据 支持关系数据的查询 API无需定义各种路由,完全数据驱动 无需管理API版本,一个版本持续演进 支持大部分主流开发语言和平台 强大的配套开发工具 使用方法 下面我们通过搭建一个SpaceX的新闻网站来直观学习graphQL的基本使用方法,所有数据由 官方API 获得。 GraphQL服务端 服务端采用node + express。新建一个node项目,安装如下依赖: $ npm i graphql express-graphql express axios 创建入口文件 server.js,里面创建express服务。使用graphQL我们只需要设置一个路由,所有的请求都由这个graphQL的request handler处理: const express = require("express"); const graphqlHTTP = require("express-graphql"); const schema = require("./schema"); const app = express(); app.use( "/graphql", graphqlHTTP({ schema, graphiql: true }) ); const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(`Server started on port ${PORT}`)); graphqlHTTP是grapql的http服务,用于处理graphql的查询请求,它接收一个options参数,其中schema是一个 GraphQLSchema实例,我们接下来定义,graphiql设置为true可以在浏览器中直接对graphQL进行调试。更多express-graphql的用法请参考 Github express-graphql。 schema 接下来我们定义schema,schema意为‘模式’,其中定义了数据模型的结构、字段的类型、模型间的关系,是graphQL的核心。 新建schema.js文件,首先定义两个数据模型:LaunchType(发射)和 RocketType(火箭)。注意字段的数据类型需要使用GraphQL定义的,不能使用js中的基本数据类型。 const { GraphQLObjectType, GraphQLInt, GraphQLString, GraphQLBoolean, GraphQLList, GraphQLSchema } = require("graphql"); const LaunchType = new GraphQLObjectType({ name: "Launch", fields: () => ({ flight_number: { type: GraphQLInt }, mission_name: { type: GraphQLString }, launch_date_local: { type: GraphQLString }, launch_success: { type: GraphQLBoolean }, rocket: { type: RocketType } }) }); const LaunchType = new GraphQLObjectType({ name: "Rocket", fields: () => ({ rocket_id: { type: GraphQLString }, rocket_name: { type: GraphQLString }, rocket_type: { type: GraphQLString } }) }); 有了数据模型之后,我们需要从数据库或者第三方API获取数据,在此我们从spacex的官方API获取。我们需要定义一个root query,root query做为所有查询的入口,处理并返回数据,更多请参考 GraphQL Root fields & resolvers。 在 schema.js中增加代码: const axios = require("axios"); const RootQuery = new GraphQLObjectType({ name: "RootQueryType", fields: { launches: { type: new GraphQLList(LaunchType), resolve(parent, args) { return axios .get("https://api.spacexdata.com/v3/launches") .then(res => res.data); } } } }); module.exports = new GraphQLSchema({ query: RootQuery }); 查询列表 完成这一步,服务端api基本搭建完成!我们看一下效果,在浏览器中输入 http://localhost:5000/graphql 将打开 Graphiql(生产环境建议禁用): 我们可以只查询所有的 flight_number: 或者更多的属性: 是不是很简单很神奇! 单个查询 我们也可以通过传入参数查询单条信息: const RootQuery = new GraphQLObjectType({ name: "RootQueryType", fields: { launch: { type: LaunchType, args: { flight_number: { type: GraphQLInt } }, resolve(parent, args) { return axios .get( `https://api.spacexdata.com/v3/launches/${ args.flight_number }` ) .then(res => res.data); } } } }); 结果: 推荐大家使用Fundebug,一款很好用的BUG监控工具~ GraphQL前端 刚刚我们都是用GraphiQL在浏览器调用接口,接下来我们看一下在前端页面中怎么调用graphql服务。前端我们使用react。 在项目根目录初始化react项目: $ npx create-react-app client 为了便于调试,在package.json中增加scripts: "start": "node server.js", "server": "nodemon server.js", "client": "npm start --prefix client", "dev":"concurrently \"npm run server\" \"npm run client\" " 样式我们使用bootswatch中的一款主题: GraphQL的客户端有多种实现,本次项目使用 Apollo,最流行的GraphQL Client。更多client请参考 GraphQL Clients。 安装依赖 安装如下依赖: $ cd client $ npm i apollo-boost react-apollo graphql 其中 apollo-boost 是apollo client本身,react-apollo 是react视图层的集成,graphql 用于解析graphql的查询语句。 设置client 修改App.js内容如下: import React, { Component } from "react"; import ApolloClient from "apollo-boost"; import { ApolloProvider } from "react-apollo"; import "./theme.css"; import "./App.css"; import logo from "./spacex-logo-light.png"; const client = new ApolloClient({ uri: "http://localhost:5000/graphql" }); class App extends Component { render() { return ( <ApolloProvider client={client}> <div className="container"> <img src={logo} id="logo" /> </div> </ApolloProvider> ); } } export default App; 和redux使用<Provider>传递store类似,react-apollo 通过 <ApolloProvider>将apollo client向下传递。 实现query 接着我们来实现显示launches的component,新增文件 components/Launches.js: import React, { Component, Fragment } from "react"; import gql from "graphql-tag"; import { Query } from "react-apollo"; import LaunchItem from "./LaunchItem"; const LAUNCHES_QUERY = gql` query LaunchesQuery { launches { flight_number mission_name launch_date_local launch_success } } `; export class Launches extends Component { render() { return ( <Fragment> <h1 className="display-4 my-3">Launches</h1> <Query query={LAUNCHES_QUERY}> {({ loading, error, data }) => { if (loading) return <h4>Loading...</h4>; if (error) console.log(error); return ( <Fragment> {data.launches.map(launch => ( <LaunchItem key={launch.flight_number} launch={launch} /> ))} </Fragment> ); }} </Query> </Fragment> ); } } export default Launches; query语句通过 graphql-tag 定义,传入 <Query> 执行获取数据并传入 LaunchItem 显示。 components/LaunchItem.js: import React from "react"; export default function LaunchItem({ launch: { flight_number, mission_name, launch_date_local, launch_success } }) { return ( <div className="card card-body mb-3"> <div className="col-md-9"> <h4>Mission: {mission_name}</h4> <p>Date: {launch_date_local}</p> </div> <div className="col-md-3"> <button className="btn btn-secondary">Launch Details</button> </div> </div> ); } 查询语句通过graphql-tag定义,然后传入<Query>执行。 运行 由于本地调试,client和server分别运行在不同的端口,所以需要先进行跨域处理,使用 cors。 // server.js const cors = require('cors'); app.use(cors()); 效果 好了,大功告成,我们来看一下效果: 结语 今天就主要介绍GraphQL工程的搭建和GraphQL Query的使用,更多关于GraphQL的内容比如 Mutation下次有空会跟大家逐步讲解。 本文灵感来源:Youtube@Traversy Media,感谢 本文Demo Github地址:Github@MudOnTire 本文Demo线上展示:Heroku@graphql-spacex-launches 关于Fundebug Fundebug专注于JavaScript、微信小程序、微信小游戏、支付宝小程序、React Native、Node.js和Java线上应用实时BUG监控。 自从2016年双十一正式上线,Fundebug累计处理了10亿+错误事件,付费客户有阳光保险、核桃编程、荔枝FM、掌门1对1、微脉、青团社等众多品牌企业。欢迎大家免费试用!

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

新手建站图文教程

目录 一、购买域名和空间二、虚拟空间配置三、上传网站源码四、域名绑定五、域名备案 一、购买域名和空间 1、什么是域名?域名(英语:Domain Name),简称域名、网域,是由一串用点分隔的名字组成的Internet上某一台计算机或计算机组的名称,用于在数据传输时标识计算机的电子方位(有时也指地理位置)。-----这是百度百科上面的介绍通俗来说,你就理解成网址吧,就是访问你的网站的网址。 2、什么是虚拟空间可以理解成存放你源代码的网络硬盘,这个硬盘在哪你不用管,你往上放源码就好了。 3、这些在哪里买?推荐在阿里云购买,直接淘宝登陆授权一下就行,不用注册,多方便。阿里云优惠券地址域名购买地址 1)域名购买进入域名购买网页之后,搜索你自己想要的域名,如果没有被注册,恭喜你,你就可以直接购买了;如果已经被别人买了,那你只能换一个咯。 加入清单之后,结

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

教程: 使用PreparedStatement访问DLA

大家都知道PreparedStatement相比手动拼写SQL有很多好处,比如: 它会自动做敏感字符的转义,防止SQL Injection攻击。 它可以帮助我们动态执行SQL,Prepare一次之后,后续执行只需要替换参数就可以了。 它可以帮助以OOP的方式来写SQL相关相关代码,因为我们是通过 PrepareSteatement.setXxx()的方式而不是字符串拼接的方式来设置参数。 等等,PreparedStatement的好处还有很多,更多可以参考这篇《JDBC Statement vs PreparedStatement – SQL Injection Example》, 上面说的很详细。 今天我们Data Lake Analytics也引入了对PreparedStatement的支持, 今天给大家演示一下,如何用 Prepare

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

MPAndroidChart 教程:开始 Getting Started

入门 本章介绍使用此库的基本设置。 添加依赖 首先,将此库的依赖项添加到项目中。如何执行此操作在此存储库的用法部分中进行了描述。Gradle是使用此库作为依赖项的推荐方法。 创建视图 要使用LineChart, BarChart, ScatterChart, CandleStickChart, PieChart, BubbleChart or RadarChart,请在.xml中定义它: <com.github.mikephil.charting.charts.LineChart android:id="@+id/chart" android:layout_width="match_parent" android:layout_height="match_parent" /> 然后从您的Activity,Fragment或其他内容中检索它: // in this example, a LineChart is initialized from xml LineChart chart = (LineChart) findViewById(R.id.chart); 或者在代码中创建它(然后将其添加到布局中): // programmatically create a LineChart LineChart chart = new LineChart(Context); // get a layout defined in xml RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout); rl.add(chart); // add the programmatically created chart 添加数据 拥有图表实例后,您可以创建数据并将其添加到图表中。此示例使用LineChart,其中Entry类表示图表中具有x和y坐标的单个条目。其他图表类型(例如BarChart)使用其他类(例如BarEntry)。 要将数据添加到图表中,请将您拥有的每个数据对象包装到Entry对象中,如下所示: YourData[] dataObjects = ...; List<Entry> entries = new ArrayList<Entry>(); for (YourData data : dataObjects) { // turn your data into Entry objects entries.add(new Entry(data.getValueX(), data.getValueY())); } 下一步,您需要将创建的List<Entry>添加到LineDataSet对象中。DataSet对象保存属于一起的数据,并允许对该数据进行单独设计。以下使用的“Label ”仅具有描述性目的,并在Legend中显示(如果已启用)。 LineDataSet dataSet = new LineDataSet(entries, "Label"); // add entries to dataset dataSet.setColor(...); dataSet.setValueTextColor(...); // styling, ... 最后一步,您需要将创建的LineDataSet对象(或多个对象)添加到LineData对象中。此对象包含由Chart实例表示的所有数据,并允许进一步样式化。创建数据对象后,您可以将其设置为图表并刷新它: LineData lineData = new LineData(dataSet); chart.setData(lineData); chart.invalidate(); // refresh 请考虑上面的场景一个非常基本的设置。有关更详细的说明,请参阅设置数据部分,它解释了如何根据示例将数据添加到各种图表类型。 造型 有关图表表面和数据的设置和样式的信息,请访问常规设置和样式部分。有关各个图表类型的更具体的样式和设置,请查看特定设置和样式Wiki页面。 参考: https://github.com/PhilJay/MPAndroidChart/wiki/Getting-Started https://blog.csdn.net/u014136472/article/details/50293767

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

Source Map入门教程

部署前端之前,开发者通常会对代码进行打包压缩,这样可以减少代码大小,从而有效提高访问速度。然而,压缩代码的报错信息是很难Debug的,因为它的行号和列号已经失真。这时就需要Source Map来还原真实的出错位置了。 为啥变换代码? 前端代码越来越复杂的情况下,开发者通常会使用webpack、UglifyJS2等工具对代码进行打包变换,这样可以减少代码大小,有效提高访问速度。关于变换代码的原因,这里不妨引用一下大神阮一峰的JavaScript Source Map 详解: 压缩,减小体积。比如jQuery 1.9的源码,压缩前是252KB,压缩后是32KB。 多个文件合并,减少HTTP请求数。 其他语言编译成JavaScript。最常见的例子就是CoffeeScript。 如何变换代码? 下面是一个简单的“hello World”程序hello.js function sayHello() { var name = "Fundebug"; var greeting = "Hello, " + Name; console.log(greeting); } sayHello(); 使用UglifyJS2对源代码进行压缩变换: uglifyjs hello.js \ -m toplevel=true \ -c unused=true,collapse_vars=true \ -o hello.min.js 压缩后的代码hello.min.js function o(){var o="Hello, "+Name;console.log(o)}o(); 为啥需要Source Map? 使用Firefox执行hello.js的报错信息是这样: ReferenceError: Name is not defined sayHello file:///Users/fundebug/sourcemap-tutorial/hello.js:4:9 <匿名> file:///Users/fundebug/sourcemap-tutorial/hello.js:8:1 而hello.min.js的报错信息是这样: ReferenceError: Name is not defined o file:///Users/fundebug/sourcemap-tutorial/hello.min.js:1:18 <匿名> file:///Users/fundebug/sourcemap-tutorial/hello.min.js:1:59 对比压缩前后的出错信息,我们会发现,错误行号和列号已经失真,且函数名也经过了变换。而对于真实的前端项目,开发者会将数十个源文件压缩为一个文件,这时,错误的列号可能多达数千,且出错的真实文件名也是很难确定的,这样的话,压缩代码的报错信息是很难Debug的。 而Source Map则可以用于还原真实的出错位置,帮助开发者更快的Debug。 什么是Source Map? 使用UglifyJS2时指定source-map选项即可生成Source Map: uglifyjs hello.js \ -m toplevel=true \ -c unused=true,collapse_vars=true \ --source-map hello.min.js.map \ --source-map-include-sources \ --source-map-root \ -o hello.min.js 各种主流前端任务管理工具,打包工具都支持生成Source Map,具体可以查看生成Source Map - Fundebug文档。 生成的hello.min.js多了sourceMappingURL,表示Source Map文件的位置。 function o(){var o="Hello, "+Name;console.log(o)}o(); //# sourceMappingURL=hello.min.js.map 生成的Source Map为hello.min.js.map: { "version": 3, "sources": ["hello.js"], "names": ["sayHello", "greeting", "Name", "console", "log"], "mappings": "AAAA,QAASA,KAEL,GACIC,GAAW,UAAYC,IAC3BC,SAAQC,IAAIH,GAGhBD", "file": "hello.min.js", "sourceRoot": "", "sourcesContent": ["function sayHello()\n{\n var name = \"Fundebug\";\n var greeting = \"Hello, \" + Name;\n console.log(greeting);\n}\n\nsayHello();\n"] } 由hello.min.js.map可知,Source Map是一个JSON文件,而它包含了代码转换前后的位置信息。也就是说,给定一个转换之后的压缩代码的位置,就可以通过Source Map获取转换之前的代码位置,反过来也一样。Source Map各个属性的含义如下: version:Source Map的版本号。 sources:转换前的文件列表。 names:转换前的所有变量名和属性名。 mappings:记录位置信息的字符串,经过编码。 file:(可选)转换后的文件名。 sourceRoot:(可选)转换前的文件所在的目录。如果与转换前的文件在同一目录,该项为空。 sourcesContent:(可选)转换前的文件内容列表,与sources列表依次对应。 Source Map真正神奇之处在于mappings属性,它记录了位置是如何对应的。JavaScript Source Map 详解已经有很好的解释,这里不再赘述。 怎样使用Source Map? 主流浏览器均支持Source Map功能,不过Chrome与Firefox需要一些简单的配置,具体步骤请参考How to enable source maps。下面以MacBook上的Chrome浏览器为例,介绍一下配置方法: 1. 开启开发者工具 使用快捷键option + command + i;或者在菜单栏选择视图->开发者->开发者工具 2. 打开设置 使用快捷键fn + F1;或者点击右上角的三个点的图标,选择Settings 3. 开启Source Map 在Sources中,选中Enable JavaScript source maps 为了测试,我写了一个简单的HTML文件hello.min.html <head> <script type="text/javascript" src="hello.min.js"></script> </head> 使用Chrome打开hello.min.html,在控制台看到的错误如下: Uncaught ReferenceError: Name is not defined at o (hello.min.js:1) at hello.min.js:1 报错的文件仍然为hello.min.js,需要刷新一下Source Map才有作用: Uncaught ReferenceError: Name is not defined at o (hello.js:4) at hello.js:8 注意,Chrome的报错信息没有列号,因此4为错误的行号。Chrome不仅可以通过Source Map还原真实的出错位置,还可以根据Source Map的sourcesContent还原出错的源代码。点击出错位置,即可跳转到源码,这样Debug将非常方便。 参考链接 JavaScript Source Map 详解 Source Map Revision 3 Proposal How to enable source maps 关于Fundebug Fundebug专注于JavaScript、微信小程序、微信小游戏、支付宝小程序、React Native、Node.js和Java实时BUG监控。 自从2016年双十一正式上线,Fundebug累计处理了6亿+错误事件,得到了Google、360、金山软件等众多知名用户的认可。欢迎免费试用! 版权声明 转载时请注明作者Fundebug以及本文地址:https://blog.fundebug.com/2017/03/13/sourcemap-tutorial/

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

MyBatis框架教程「入门起步」

今天我们就踏上学习Mybatis框架的旅程,在SSM框架中Mybatis框架是dao层的一个解决方案。相当于传统Servlet+JavaBean开发模式中JDBC的作用。具体关于MVC架构的知识可以移步「从零学习Spring MVC框架「环境搭建和MVC架构」」文章,在这一篇文章的开篇我详细阐述了关于MVC架构的知识。 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs「Plain Old Java Objects,普通的 Java对象」映射成数据库中的记录,它是dao层的一个解决方案。 什么需求催生了MyBatis这种框架的产生呢?Mybatis框架比较重要的是:Mybatis自动将sql执行结果映射至java对象。我们知道目前流行的编程语言,例如Java,C#是面向对象的编程语言;但是主流的数据库产品,例如:Oracle,Mysql 等都是关系型数据库,编程语言和底层数据的发展不协调,催生出了ORM框架。我们可以理解为ORM框架可作为面向对象语言和数据库之间的桥梁。我们将要学习的MyBatis的设计思想和ORM很相似。 起步首先将mybatis-x.x.x.jar文件置于 classpath 中即可。由于需要连接数据库我们还需要驱动包。 如果使用 Maven 来构建项目,则需将下面的 dependency 代码置于 pom.xml 文件中: <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>x.x.x</version> </dependency> 构建 SqlSessionFactory每个基于 MyBatis 的应用都是以一个 SqlSessionFactory的实例为中心的。SqlSessionFactory的实例可以通过SqlSessionFactoryBuilder获得,关于SqlSession的介绍我们在文章末尾展开。 SqlSessionFactoryBuilder可以从 XML 配置文件或一个预先定制的 Configuration的实例构建出SqlSessionFactory的实例。SqlSession产生的第一步就是要利用SqlSessionFactoryBuilder来获取工厂SqlSessionFactory,再获得SqlSession。SqlSessionFactoryBuilder有五个build()方法,每一种都允许你从不同的资源中创建一个SqlSession实例。 SqlSessionFactory build(InputStream inputStream) SqlSessionFactory build(InputStream inputStream, String environment) SqlSessionFactory build(InputStream inputStream, Properties properties) SqlSessionFactory build(InputStream inputStream, String env, Properties props) SqlSessionFactorybuild(Configuration config) 以上五种 build()方法中,第一种是最常用的一种,在这里就不进行讲解。这里我们使用: //加载 核心配置文件 InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); //创建sqlsession工厂 -->相当于connection SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //获取sqlsession -->相当于执行sql语句对象 sqlSession = sqlSessionFactory.openSession(); 3. mybatis-config.xml XML配置文件中包含了对 MyBatis 系统的核心设置,包含获取数据库连接实例的数据源(DataSource)和决定事务作用域和控制方式的事务管理器。XML 配置文件的详细内容下方探讨,这里先给出一个简单的示例: <?xml version="1.0"encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTDConfig 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 配置环境 --> <environments default="jujidi"> <environment id="jujidi"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/dbname"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!-- 加载映射文件 --> <mappers> <mapper resource="com/jujidi/test/TestMapper.xml" /> </mappers> </configuration> 当然,还有很多可以在XML 文件中进行配置,上面的示例指出的则是最关键的部分。要注意 XML 头部的声明,用来验证 XML 文档正确性。environment 元素体中包含了事务管理和连接池的配置。mappers 元素则是包含一组 mapper 映射器(这些 mapper 的 XML 文件包含了 SQL 代码和映射定义信息)关于事务管理器:在 MyBatis 中有两种类型的事务管理器JDBC – 这个配置就是直接使用了 JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务作用域MANAGED – 这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文) TestMapper.xml <?xml version="1.0"encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTDMapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.jujidi.model.User"> <!-- 通过id返回数据 --> <select id="load"resultType="map"> select * from user where user_id=1 </select> </mapper> namespace:是对此mapper 的唯一标识,通过select标签进行声明一个sql语句。 select中的id属性是在此mapper映射文件中sql语句的唯一id,我们可以通过namespace.id来定位这一条sql语句 MyBatisTest.java public class MybatisTest { public static void main(String[] args ) { SqlSession sqlSession = null; try{ //加载核心配置文件 InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); //创建sqlsession工厂 -->相当于connection SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //获取sqlsession -->相当于执行sql语句对象 sqlSession = sqlSessionFactory.openSession(); //执行sql Map<String , Object> map = sqlSession.selectOne("com.jujidi.model.User.load"); System.out.println(map); }catch(IOException e){ // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(sqlSession!=null){ sqlSession.close(); } } } } 到这里环境环境搭建完毕,讲解大体流程: MyBatisTest.java类中进行测试搭建的环境,首先加载核心配置文件mybatis-config.xml,此配置文件用来配置环境参数和加载映射文件。然后创建sqlsession工厂,这个工厂就要通过刚刚加载的mybatis-config.xml配置文件来build。通过工厂就可以生产sqlsession了,sqlsession有很多方法,我们执行selectOne方法来执行映射文件中的SQL,这就必须在selectOne方法中填写映射文件中对应SQL的地址,也就是全限定类名来定位。在映射文件中进行操作数据库把结果进行返回,打印输出。好了这里差不多把环境搭建完毕后的流程走了一遍,算是对MyBatis的一个入门和起步,接下来我们就来谈一下SqlSessionFactory和SqlSession. SqlSessionFactory和SqlSessionSqlSessionFactory是MyBatis非常重要的对象,他是单个数据库映射关系经过编译后的内存镜像。 SqlSessionFactory的实例可以通过SqlSessionFactoryBuilder对象来获得,而SqlSessionFactoryBuilder从XML配置文件等中构建出SqlSessionFactory的实例。SqlSessionFactory一旦创建,在应用的执行期间都存在,其线程也是安全的。SqlSession类似于JDBC中的Connection。它是应用程序与持久层之间执行交互操作的一个单线程对象。它底层封装了JDBC连接,线程是不安全的。 原文发布时间为:2018-07-28本文作者:王久一本文来自云栖社区合作伙伴“Web项目聚集地”,了解相关信息可以关注“Web项目聚集地”。

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

Protocol Buffers入门教程

什么是Protocol Buffers 先看官网定义: protocol buffers – a language-neutral, platform-neutral, extensible way of serializing structured data for use in communications protocols, data storage, and more. Protocol Buffers 是一种结构化数据的存储格式,可以用于结构化数据的序列化和反序列化。它很适合做数据存储、 RPC 数据交换格式。 Protocol Buffers的作用可以类比JSON、XML。 对于传输双方,如果约定好使用Protocol Buffer为数据传输的格式,那么这将是一种比JSON和XML都高效轻便的途径。 Protocol Buffers支持多种编程语言,包括C++、Java、Python、Go、C#等。 安装Protocol Buffers 1、官网下载压缩包 2、解压 tar -zxvf protobuf-all-3.6.0.tar.gz 3、protobuf的包需要自己编译 cd protobuf-3.6.0 ./configure make make install 4、在protobuf-3.6.0目录下有对应着各种语言的文件夹,每个文件夹下都有README.md,里面有相应的安装步骤。对于python: cd protobuf-3.6.0/python python setup.py build python setup.py test python setup.py install 5、到此为止,protobuf的python版本已经安装完成,可在命令行键入protoc试试。 Demo 1、创建addressbook.proto文件。.proto文件定义了要序列化的数据结构。 syntax = "proto2"; package tutorial; message Person { required string name = 1; required int32 id = 2; optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phones = 4; } message AddressBook { repeated Person people = 1; } 2、编译addressbook.proto protoc --python_out=/Users/ya/developer/protoc-test addressbook.proto 这一条命令执行完后会在你指定的目录下生成addressbook_pb2.py文件。 addressbook_pb2.py会提供关于所定义的数据结构的操作方法。 3、编写writer.py,负责序列化数据并保存到文件 # See README.txt for information and build instructions. import addressbook_pb2 import sys try: raw_input # Python 2 except NameError: raw_input = input # Python 3 # This function fills in a Person message based on user input. def PromptForAddress(person): person.id = int(raw_input("Enter person ID number: ")) person.name = raw_input("Enter name: ") email = raw_input("Enter email address (blank for none): ") if email != "": person.email = email while True: number = raw_input("Enter a phone number (or leave blank to finish): ") if number == "": break phone_number = person.phones.add() phone_number.number = number type = raw_input("Is this a mobile, home, or work phone? ") if type == "mobile": phone_number.type = addressbook_pb2.Person.MOBILE elif type == "home": phone_number.type = addressbook_pb2.Person.HOME elif type == "work": phone_number.type = addressbook_pb2.Person.WORK else: print("Unknown phone type; leaving as default value.") # Main procedure: Reads the entire address book from a file, # adds one person based on user input, then writes it back out to the same # file. if len(sys.argv) != 2: print("Usage:", sys.argv[0], "ADDRESS_BOOK_FILE") sys.exit(-1) address_book = addressbook_pb2.AddressBook() # Read the existing address book. try: with open(sys.argv[1], "rb") as f: address_book.ParseFromString(f.read()) except IOError: print(sys.argv[1] + ": File not found. Creating a new file.") # Add an address. PromptForAddress(address_book.people.add()) # Write the new address book back to disk. with open(sys.argv[1], "wb") as f: f.write(address_book.SerializeToString()) 5、执行writer.py python writer.py addressbook.data 执行完脚本后数据将会序列化并存储到addressbook.data中。 6、编写reader.py,负责读取文件并反序列化数据 import addressbook_pb2 import sys # Iterates though all people in the AddressBook and prints info about them. def ListPeople(address_book): for person in address_book.people: print "Person ID:", person.id print "Name:", person.name if person.email != "": print "E-mail address:", person.email for phone_number in person.phones: if phone_number.type == addressbook_pb2.Person.MOBILE: print "Mobile phone :", elif phone_number.type == addressbook_pb2.Person.HOME: print "Home phone :", elif phone_number.type == addressbook_pb2.Person.WORK: print "Work phone :", print(phone_number.number) # Main procedure: Reads the entire address book from a file and prints all # the information inside. if len(sys.argv) != 2: print("Usage:", sys.argv[0], "ADDRESS_BOOK_FILE") sys.exit(-1) address_book = addressbook_pb2.AddressBook() # Read the existing address book. with open(sys.argv[1], "rb") as f: address_book.ParseFromString(f.read()) ListPeople(address_book) 7、执行reader.py python reader.py addressbook.data 输出结果示例: Person ID: 1 Name: kanon E-mail address: 540004716@qq.com Mobile phone : 123456 两个很重要的方法 SerializeToString( ):serializes the message and returns it as a string. ParseFromString( data ):parses a message from the given string. Protocol Buffers 相比 XML are simpler are 3 to 10 times smaller are 20 to 100 times faster are less ambiguous generate data access classes that are easier to use programmatically 在ODPS(MaxCompute)中的应用 ODPS的Tunnel HTTP Server采用了Protobuf作为其序列化机制。客户端在上传数据时,需要先对结构化数据进行序列化(生成二进制流),Tunnel服务端接收到数据后,(对二进制流)执行反序列化,还原出结构化数据,写到ODPS表中。

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

Memcached安装教程及使用

Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载 Table of contents 安装 使用 在spring中使用 安装 下载下来memcached.exe 切换到memcached.exe所在路径 输入memcached -d install win + r 输入 services.msc打开window服务 随便选中一个输入memcached就可以查看到安装好的服务,右击启动它,然后关闭窗口 使用 新建java工程或者maven工程 导入三个必备的依赖,fastjson-1.2.3,slf4j-api-1.7.5,xmemcached-2.3.2 main方法中加入 MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("127.0.0.1:11211")); builder.setSessionLocator(new KetamaMemcachedSessionLocator()); try { MemcachedClient memcachedClient =builder.build(); //在这里写入测试代码 memcachedClient.shutdown(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (MemcachedException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } 测试一定时间后数据是否还能取出来 永久时间,测试重启服务之后先前存储的数据是否还能取出来 delete 自动增长 时效 memcachedClient.set("testTime",2,"testTimeValue"); String testTime = memcachedClient.get("testTime"); System.out.println("testTime = " + testTime); TimeUnit.SECONDS.sleep(4); System.out.println("4s 过去了"); String valueExist = memcachedClient.get(testTime); System.out.println("valueExist = " + valueExist); 输出: testTime = testTimeValue 4s 过去了 valueExist = null 恢复 //存储,然后关闭掉服务 memcachedClient.set("test",0,"testValue"); String testTime=memcachedClient.get("test"); System.out.println("testTime="+testTime); System.out.println("存储成功"); 输出: testTime = testValue 存储成功 //关闭掉服务后的重启 String testTime = memcachedClient.get("test"); System.out.println("testTime = " + testTime); System.out.println("取值失败"); 输出: testTime = null 取值失败 delete memcachedClient.set("test",0,"testValue"); String getVal = memcachedClient.get("test"); System.out.println("getVal = " + getVal); memcachedClient.delete("test"); System.out.println("after delete ..."); getVal = memcachedClient.get("test"); System.out.println("getVal = " + getVal); 输出: getVal = testValue after delete ... getVal = null 自动增长 //三个参数,第一个指定键,第二个指定递增的幅度大小,第三个指定当key不存在的情况下的初始值 for (int i = 0; i < 5; i++) { memcachedClient.incr("博客的赞",1,20); String point = memcachedClient.get("博客的赞"); System.out.println("point = " + point); } 输出: point = 20 point = 21 point = 22 point = 23 point = 24 关于incr的用法,值得警惕的是,它的值虽然看起来是一个数字,实际上正如代码中的String point = memcachedClient.get("博客的赞"); 其实是一个字符串,所以会出现如下错误 memcachedClient.set("博客的赞1",0,10); int str = memcachedClient.get("博客的赞1"); System.out.println("str1 = " + str); memcachedClient.incr("博客的赞1",2,22); str = memcachedClient.get("博客的赞1"); System.out.println("str2 = " + str); 输出: net.rubyeye.xmemcached.exception.MemcachedClientException: cannot increment or decrement non-numeric value,key=博客的赞1 at net.rubyeye.xmemcached.command.Command.decodeError(Command.java:267) .. at com.google.code.yanf4j.nio.impl.NioController.onRead(NioController.java:157) at com.google.code.yanf4j.nio.impl.Reactor.dispatchEvent(Reactor.java:323) at com.google.code.yanf4j.nio.impl.Reactor.run(Reactor.java:180) str1 = 10 输出的顺序不同,注意输出的异常栈信息的第一条和后面的几条就指明nio.impl.Reactor.run,线程的,这儿就不深入展开了 spring 新建一个maven工程 pom.xml 在resource中新建sping-config.xml spring单元测试代码骨架 测试代码 骨架 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:spring-config.xml") public class TestMem { @Autowired private MemcachedClient memcachedClient; @Test public void test1(){ //测试代码部分 } } 测试代码 memcachedClient.set("springData",3,"dataVal"); String str = memcachedClient.get("springData"); System.out.println("str = " + str); 输出: str = dataVal 还可以存储对象,不过该对象必须实现Serializable接口,不然会报错java.io.NotSerializableException: Teacher, 实现接口后 import lombok.Data; import java.io.Serializable; @Data public class Teacher implements Serializable { private int age; private String name; } 关于@Data关我在另一篇博客中有介绍lombok Teacher teacher = new Teacher(); teacher.setAge(3); teacher.setName("23"); memcachedClient.set("te", 0, teacher); Teacher teacher1 = memcachedClient.get("te"); System.out.println("teacher1 = " + teacher1); 输出: teacher1 = Teacher(age=3, name=23) pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.selton</groupId> <artifactId>DemoMemSpring</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.11.RELEASE</version> </dependency> <dependency> <groupId>com.googlecode.xmemcached</groupId> <artifactId>xmemcached</artifactId> <version>2.0.0</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.11.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> </project> config <?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <bean id="memcachedClient" name="memcachedClient" class="net.rubyeye.xmemcached.utils.XMemcachedClientFactoryBean"> <property name="servers"> <!--配置端口,另加入的话,空格隔开--> <value>127.0.0.1:11211</value> </property> <property name="weights"> <list> <!--设置不同端口的权重,这里只有一个端口--> <value>1</value> </list> </property> <property name="sessionLocator"> <bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator"></bean> </property> <property name="transcoder"> <bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder" /> </property> <property name="bufferAllocator"> <bean class="net.rubyeye.xmemcached.buffer.SimpleBufferAllocator"></bean> </property> </bean> </beans>

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

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

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

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

用户登录
用户注册