nginx自定义变量与内置预定义变量(获取GET参数值,HEADER参数值等)

 nginx  nginx自定义变量与内置预定义变量(获取GET参数值,HEADER参数值等)已关闭评论
3月 242021
 

总览
nginx可以使用变量简化配置与提高配置的灵活性,所有的变量值都可以通过这种方式引用:

$变量名

而nginx中的变量分为两种,自定义变量与内置预定义变量

内置变量
声明
可以在sever,http,location等标签中使用set命令(非唯一)声明变量,语法如下

set $变量名 变量值

注意nginx中的变量必须都以$开头。

可见性
nginx的配置文件中所有使用的变量都必须是声明过的,否则nginx会无法启动并打印相关异常日志

nginx变量的一个有趣的特性就是nginx中没一个变量都是全局可见的,而他们又不是全局变量。比如下面这个例子

location a/ {
return 200 $a
}

location b/ {
set $a hello nginx
return 200 $a
}

由于变量是全局可见的所以nginx启动不会报错,而第一个location中并不知道$a的具体值因此返回的响应结果为一个空字符串。

在不同层级的标签中声明的变量性的可见性规则如下:

location标签中声明的变量中对这个location块可见
server标签中声明的变量对server块以及server块中的所有子块可见
http标签中声明的变量对http块以及http块中的所有子块可见
内置预定义变量
内置预定义变量即无需声明就可以使用的变量,通常包括一个http请求或响应中一部分内容的值,以下为一些常用的内置预定义变量

变量名 定义
$arg_PARAMETER GET请求中变量名PARAMETER参数的值。
$args 这个变量等于GET请求中的参数。例如,foo=123&bar=blahblah;这个变量只可以被修改
$binary_remote_addr 二进制码形式的客户端地址。
$body_bytes_sent 传送页面的字节数
$content_length 请求头中的Content-length字段。
$content_type 请求头中的Content-Type字段。
$cookie_COOKIE cookie COOKIE的值。
$document_root 当前请求在root指令中指定的值。
$document_uri 与$uri相同。
$host 请求中的主机头(Host)字段,如果请求中的主机头不可用或者空,则为处理请求的server名称(处理请求的server的server_name指令的值)。值为小写,不包含端口。
$hostname 机器名使用 gethostname系统调用的值
$http_HEADER HTTP请求头中的内容,HEADER为HTTP请求中的内容转为小写,-变为_(破折号变为下划线),例如:$http_user_agent(Uaer-Agent的值);
$sent_http_HEADER HTTP响应头中的内容,HEADER为HTTP响应中的内容转为小写,-变为_(破折号变为下划线),例如: $sent_http_cache_control, $sent_http_content_type…;
$is_args 如果$args设置,值为”?”,否则为””。
$limit_rate 这个变量可以限制连接速率。
$nginx_version 当前运行的nginx版本号。
$query_string 与$args相同。
$remote_addr 客户端的IP地址。
$remote_port 客户端的端口。
$remote_user 已经经过Auth Basic Module验证的用户名。
$request_filename 当前连接请求的文件路径,由root或alias指令与URI请求生成。
$request_body 这个变量(0.7.58+)包含请求的主要信息。在使用proxy_pass或fastcgi_pass指令的location中比较有意义。
$request_body_file 客户端请求主体信息的临时文件名。
$request_completion 如果请求成功,设为”OK”;如果请求未完成或者不是一系列请求中最后一部分则设为空。
$request_method 这个变量是客户端请求的动作,通常为GET或POST。包括0.8.20及之前的版本中,这个变量总为main request中的动作,如果当前请求是一个子请求,并不使用这个当前请求的动作。
$request_uri 这个变量等于包含一些客户端请求参数的原始URI,它无法修改,请查看$uri更改或重写URI。
$scheme 所用的协议,比如http或者是https,比如rewrite ^(.+)$ $scheme://example.com$1 redirect;
$server_addr 服务器地址,在完成一次系统调用后可以确定这个值,如果要绕开系统调用,则必须在listen中指定地址并且使用bind参数。
$server_name 服务器名称。
$server_port 请求到达服务器的端口号。
$server_protocol 请求使用的协议,通常是HTTP/1.0或HTTP/1.1。
$uri 请求中的当前URI(不带请求参数,参数位于a r g s ) , 不 同 于 浏 览 器 传 递 的 args),不同于浏览器传递的args),不同于浏览器传递的request_uri的值,它可以通过内部重定向,或者使用index指令进行修改。不包括协议和主机名,例如/foo/bar.html

原文链接:https://blog.csdn.net/m0_37556444/article/details/84563520

mybatis下limit有参数计算时的写法

 开发  mybatis下limit有参数计算时的写法已关闭评论
4月 232020
 

mybatis下limit如果想做分页,对limit做参数计算时:

错误的写法:

<select id=”queryMyApplicationRecord” parameterType=”MyApplicationRequest” resultMap=”myApplicationMap”>
SELECT
a.*,
FROM
tb_user a
WHERE 1=1
<if test=”ids != null and ids.size()!=0″>
AND a.id IN
<foreach collection=”ids” item=”id” index=”index”
open=”(” close=”)” separator=”,”>
#{id}
</foreach>
</if>
<if test=”statusList != null and statusList.size()!=0″>
AND a.status IN
<foreach collection=”statusList” item=”status” index=”index”
open=”(” close=”)” separator=”,”>
#{status}
</foreach>
</if>
ORDER BY a.create_time desc
LIMIT (#{pageNo}-1)*#{pageSize},#{pageSize}; // 错误
</select>
在MyBatis中LIMIT之后的语句不允许的变量不允许进行算数运算,会报错。

正确的写法一:
<select id=”queryMyApplicationRecord” parameterType=”MyApplicationRequest” resultMap=”myApplicationMap”>
SELECT
a.*,
FROM
tb_user a
WHERE 1=1
<if test=”ids != null and ids.size()!=0″>
AND a.id IN
<foreach collection=”ids” item=”id” index=”index”
open=”(” close=”)” separator=”,”>
#{id}
</foreach>
</if>
<if test=”statusList != null and statusList.size()!=0″>
AND a.status IN
<foreach collection=”statusList” item=”status” index=”index”
open=”(” close=”)” separator=”,”>
#{status}
</foreach>
</if>
ORDER BY a.create_time desc
LIMIT ${(pageNo-1)*pageSize},${pageSize}; (正确)
</select>
正确的写法二:(推荐)
<select id=”queryMyApplicationRecord” parameterType=”MyApplicationRequest” resultMap=”myApplicationMap”>
SELECT
a.*,
FROM
tb_user a
WHERE 1=1
<if test=”ids != null and ids.size()!=0″>
AND a.id IN
<foreach collection=”ids” item=”id” index=”index”
open=”(” close=”)” separator=”,”>
#{id}
</foreach>
</if>
<if test=”statusList != null and statusList.size()!=0″>
AND a.status IN
<foreach collection=”statusList” item=”status” index=”index”
open=”(” close=”)” separator=”,”>
#{status}
</foreach>
</if>
ORDER BY a.create_time desc
LIMIT #{offSet},#{limit}; (推荐,代码层可控)
</select>
分析:方法二的写法,需要再请求参数中额外设置两个get函数,如下:
@Data
public class QueryParameterVO {

private List<String> ids;

private List<Integer> statusList;

// 前端传入的页码
private int pageNo; // 从1开始

// 每页的条数
private int pageSize;

// 数据库的偏移
private int offSet;

// 数据库的大小限制
private int limit;

// 这里重写offSet和limit的get方法
public int getOffSet() {
return (pageNo-1)*pageSize;
}

public int getLimit() {
return pageSize;
}
}

 

swift 闭包使用$0和$1等代替参数介绍

 swift  swift 闭包使用$0和$1等代替参数介绍已关闭评论
3月 162020
 

swift自动为闭包提供参数名缩写功能,可以直接通过$0$1、$2等…来表示闭包中的第一个第二个、第三个参数及后续的参数,并且对应的参数类型会根据函数类型来进行判断。如下代码:

  • 不使用$0 $1这些来代替
let nbs = [10,15,13,14,23,26]
snbs = nbs.sorted(by: { (a, b) -> Bool in
  return a < b
})
print("sorted -" + "\(snbs)") 
  • 使用$0,$1

let nbs = [10,15,13,14,23,26]
var snbs = nbs.sorted(by: {$0 < $1})
print(“sorted -” + “\(snbs)”)

可以发现使用$0、$1的话,参数类型可以自动判断,并且in关键字也可以省略,也就是只用写函数体就可以了, 确实方便。

以太坊客户端Geth命令用法-参数详解

 eth, 区块链  以太坊客户端Geth命令用法-参数详解已关闭评论
10月 162018
 

geth的命令行详解,备用。

geth在以太坊智能合约开发中最常用的工具(必备开发工具),一个多用途的命令行工具。
熟悉Geth可以让我们有更好的效率,大家可收藏起来作为Geth命令用法手册。 本文主要是对geth help的翻译,基于最新的geth 1.7.3-stable版本。

命令用法

geth [选项] 命令 [命令选项] [参数…]

版本:

1.7.3-stable

命令:

account    管理账户
attach     启动交互式JavaScript环境(连接到节点)
bug        上报bug Issues
console    启动交互式JavaScript环境
copydb     从文件夹创建本地链
dump       Dump(分析)一个特定的块存储
dumpconfig 显示配置值
export     导出区块链到文件
import     导入一个区块链文件
init       启动并初始化一个新的创世纪块
js         执行指定的JavaScript文件(多个)
license    显示许可信息
makecache  生成ethash验证缓存(用于测试)
makedag    生成ethash 挖矿DAG(用于测试)
monitor    监控和可视化节点指标
removedb   删除区块链和状态数据库
version    打印版本号
wallet     管理Ethereum预售钱包
help,h     显示一个命令或帮助一个命令列表

ETHEREUM选项:

--config value          TOML 配置文件
--datadir “xxx”         数据库和keystore密钥的数据目录
--keystore              keystore存放目录(默认在datadir内)
--nousb                 禁用监控和管理USB硬件钱包
--networkid value       网络标识符(整型, 1=Frontier, 2=Morden (弃用), 3=Ropsten, 4=Rinkeby) (默认: 1)
--testnet               Ropsten网络:预先配置的POW(proof-of-work)测试网络
--rinkeby               Rinkeby网络: 预先配置的POA(proof-of-authority)测试网络
--syncmode "fast"       同步模式 ("fast", "full", or "light")
--ethstats value        上报ethstats service  URL (nodename:[email protected]:port)
--identity value        自定义节点名
--lightserv value       允许LES请求时间最大百分比(0 – 90)(默认值:0) 
--lightpeers value      最大LES client peers数量(默认值:20)
--lightkdf              在KDF强度消费时降低key-derivation RAM&CPU使用

开发者(模式)选项:

--dev               使用POA共识网络,默认预分配一个开发者账户并且会自动开启挖矿。
--dev.period value  开发者模式下挖矿周期 (0 = 仅在交易时) (默认: 0)

ETHASH 选项:

--ethash.cachedir                        ethash验证缓存目录(默认 = datadir目录内)
--ethash.cachesinmem value               在内存保存的最近的ethash缓存个数  (每个缓存16MB ) (默认: 2)
--ethash.cachesondisk value              在磁盘保存的最近的ethash缓存个数 (每个缓存16MB) (默认: 3)
--ethash.dagdir ""                       存ethash DAGs目录 (默认 = 用户hom目录)
--ethash.dagsinmem value                 在内存保存的最近的ethash DAGs 个数 (每个1GB以上) (默认: 1)
--ethash.dagsondisk value                在磁盘保存的最近的ethash DAGs 个数 (每个1GB以上) (默认: 2)

交易池选项:

--txpool.nolocals            为本地提交交易禁用价格豁免
--txpool.journal value       本地交易的磁盘日志:用于节点重启 (默认: "transactions.rlp")
--txpool.rejournal value     重新生成本地交易日志的时间间隔 (默认: 1小时)
--txpool.pricelimit value    加入交易池的最小的gas价格限制(默认: 1)
--txpool.pricebump value     价格波动百分比(相对之前已有交易) (默认: 10)
--txpool.accountslots value  每个帐户保证可执行的最少交易槽数量  (默认: 16)
--txpool.globalslots value   所有帐户可执行的最大交易槽数量 (默认: 4096)
--txpool.accountqueue value  每个帐户允许的最多非可执行交易槽数量 (默认: 64)
--txpool.globalqueue value   所有帐户非可执行交易最大槽数量  (默认: 1024)
--txpool.lifetime value      非可执行交易最大入队时间(默认: 3小时)

性能调优的选项:

--cache value                分配给内部缓存的内存MB数量,缓存值(最低16 mb /数据库强制要求)(默认:128)
--trie-cache-gens value      保持在内存中产生的trie node数量(默认:120)

帐户选项:

--unlock value              需解锁账户用逗号分隔
--password value            用于非交互式密码输入的密码文件

API和控制台选项:

--rpc                       启用HTTP-RPC服务器
--rpcaddr value             HTTP-RPC服务器接口地址(默认值:“localhost”)
--rpcport value             HTTP-RPC服务器监听端口(默认值:8545)
--rpcapi value              基于HTTP-RPC接口提供的API
--ws                        启用WS-RPC服务器
--wsaddr value              WS-RPC服务器监听接口地址(默认值:“localhost”)
--wsport value              WS-RPC服务器监听端口(默认值:8546)
--wsapi  value              基于WS-RPC的接口提供的API
--wsorigins value           websockets请求允许的源
--ipcdisable                禁用IPC-RPC服务器
--ipcpath                   包含在datadir里的IPC socket/pipe文件名(转义过的显式路径)
--rpccorsdomain value       允许跨域请求的域名列表(逗号分隔)(浏览器强制)
--jspath loadScript         JavaScript加载脚本的根路径(默认值:“.”)
--exec value                执行JavaScript语句(只能结合console/attach使用)
--preload value             预加载到控制台的JavaScript文件列表(逗号分隔)

网络选项:

--bootnodes value    用于P2P发现引导的enode urls(逗号分隔)(对于light servers用v4+v5代替)
--bootnodesv4 value  用于P2P v4发现引导的enode urls(逗号分隔) (light server, 全节点)
--bootnodesv5 value  用于P2P v5发现引导的enode urls(逗号分隔) (light server, 轻节点)
--port value         网卡监听端口(默认值:30303)
--maxpeers value     最大的网络节点数量(如果设置为0,网络将被禁用)(默认值:25)
--maxpendpeers value    最大尝试连接的数量(如果设置为0,则将使用默认值)(默认值:0)
--nat value             NAT端口映射机制 (any|none|upnp|pmp|extip:<IP>) (默认: “any”)
--nodiscover            禁用节点发现机制(手动添加节点)
--v5disc                启用实验性的RLPx V5(Topic发现)机制
--nodekey value         P2P节点密钥文件
--nodekeyhex value      十六进制的P2P节点密钥(用于测试)

矿工选项:

--mine                  打开挖矿
--minerthreads value    挖矿使用的CPU线程数量(默认值:8)
--etherbase value       挖矿奖励地址(默认=第一个创建的帐户)(默认值:“0”)
--targetgaslimit value  目标gas限制:设置最低gas限制(低于这个不会被挖?) (默认值:“4712388”)
--gasprice value        挖矿接受交易的最低gas价格
--extradata value       矿工设置的额外块数据(默认=client version)

GAS价格选项:

--gpoblocks value      用于检查gas价格的最近块的个数  (默认: 10)
--gpopercentile value  建议gas价参考最近交易的gas价的百分位数,(默认: 50)

虚拟机的选项:

--vmdebug        记录VM及合约调试信息

日志和调试选项:

--metrics            启用metrics收集和报告
--fakepow            禁用proof-of-work验证
--verbosity value    日志详细度:0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail (default: 3)
--vmodule value      每个模块详细度:以 <pattern>=<level>的逗号分隔列表 (比如 eth/*=6,p2p=5)
--backtrace value    请求特定日志记录堆栈跟踪 (比如 “block.go:271”)
--debug                     突出显示调用位置日志(文件名及行号)
--pprof                     启用pprof HTTP服务器
--pprofaddr value           pprof HTTP服务器监听接口(默认值:127.0.0.1)
--pprofport value           pprof HTTP服务器监听端口(默认值:6060)
--memprofilerate value      按指定频率打开memory profiling    (默认:524288)
--blockprofilerate value    按指定频率打开block profiling    (默认值:0)
--cpuprofile value          将CPU profile写入指定文件
--trace value               将execution trace写入指定文件

WHISPER实验选项:

--shh                        启用Whisper
--shh.maxmessagesize value   可接受的最大的消息大小 (默认值: 1048576)
--shh.pow value              可接受的最小的POW (默认值: 0.2)

弃用选项:

--fast     开启快速同步
--light    启用轻客户端模式

其他选项:

–help, -h    显示帮助
转自:https://learnblockchain.cn/2017/11/29/geth_cmd_options/

nodejs中使用yargs 模块处理命令行参数

 Nodejs  nodejs中使用yargs 模块处理命令行参数已关闭评论
6月 152017
 

yargs 模块

shelljs 只解决了如何调用 shell 命令,而 yargs 模块能够解决如何处理命令行参数。它也需要安装。

$ npm install --save yargs

yargs 模块提供 argv 对象,用来读取命令行参数。请看改写后的 hello 。

#!/usr/bin/env node var argv = require('yargs').argv; console.log('hello ', argv.name); 

使用时,下面两种用法都可以。

$ hello --name=tom
hello tom

$ hello --name tom
hello tom

也就是说,process.argv 的原始返回值如下。

$ node hello --name=tom [ 'node', '/path/to/myscript.js', '--name=tom' ] 

yargs 可以上面的结果改为一个对象,每个参数项就是一个键值对。

var argv = require('yargs').argv;  // $ node hello --name=tom // argv = { //   name: tom // }; 

如果将 argv.name 改成 argv.n,就可以使用一个字母的短参数形式了。

$ hello -n tom
hello tom

可以使用 alias 方法,指定 name 是 n 的别名。

#!/usr/bin/env node var argv = require('yargs') .alias('n', 'name') .argv; console.log('hello ', argv.n); 

这样一来,短参数和长参数就都可以使用了。

$ hello -n tom
hello tom
$ hello --name tom
hello tom

argv 对象有一个下划线(_)属性,可以获取非连词线开头的参数。

#!/usr/bin/env node var argv = require('yargs').argv; console.log('hello ', argv.n); console.log(argv._); 

用法如下。

$ hello A -n tom B C
hello  tom [ 'A', 'B', 'C' ] 

yargs命令行参数的配置

yargs 模块还提供3个方法,用来配置命令行参数。

  • demand:是否必选
  • default:默认值
  • describe:提示
#!/usr/bin/env node var argv = require('yargs') .demand(['n']) .default({n: 'tom'}) .describe({n: 'your name'}) .argv; console.log('hello ', argv.n); 

上面代码指定 n 参数不可省略,默认值为 tom,并给出一行提示。

options 方法允许将所有这些配置写进一个对象。

#!/usr/bin/env node var argv = require('yargs') .option('n', { alias : 'name', demand: true, default: 'tom', describe: 'your name', type: 'string' }) .argv; console.log('hello ', argv.n); 

有时,某些参数不需要值,只起到一个开关作用,这时可以用 boolean 方法指定这些参数返回布尔值。

#!/usr/bin/env node var argv = require('yargs') .boolean(['n']) .argv; console.log('hello ', argv.n); 

上面代码中,参数 n 总是返回一个布尔值,用法如下。

$ hello
hello false $ hello -n
hello true $ hello -n tom
hello true 

boolean 方法也可以作为属性,写入 option 对象。

#!/usr/bin/env node var argv = require('yargs') .option('n', { boolean: true }) .argv; console.log('hello ', argv.n); 

yargs帮助信息

yargs 模块提供以下方法,生成帮助信息。

  • usage:用法格式
  • example:提供例子
  • help:显示帮助信息
  • epilog:出现在帮助信息的结尾
#!/usr/bin/env node var argv = require('yargs') .option('f', { alias : 'name', demand: true, default: 'tom', describe: 'your name', type: 'string' }) .usage('Usage: hello [options]') .example('hello -n tom', 'say hello to Tom') .help('h') .alias('h', 'help') .epilog('copyright 2015') .argv; console.log('hello ', argv.n); 

执行结果如下。

$ hello -h

Usage: hello [options] Options: -f, --name  your name [string] [required] [default: "tom"] -h, --help  Show help [boolean] Examples: hello -n tom  say hello to Tom

copyright 2015 

yargs子命令

yargs 模块还允许通过 command 方法,设置 Git 风格的子命令。

#!/usr/bin/env node var argv = require('yargs') .command("morning", "good morning", function (yargs) { console.log("Good Morning"); }) .command("evening", "good evening", function (yargs) { console.log("Good Evening"); }) .argv; console.log('hello ', argv.n); 

用法如下。

$ hello morning -n tom
Good Morning
hello tom

可以将这个功能与 shellojs 模块结合起来。

#!/usr/bin/env node require('shelljs/global'); var argv = require('yargs') .command("morning", "good morning", function (yargs) { echo("Good Morning"); }) .command("evening", "good evening", function (yargs) { echo("Good Evening"); }) .argv; console.log('hello ', argv.n); 

每个子命令往往有自己的参数,这时就需要在回调函数中单独指定。回调函数中,要先用 reset 方法重置 yargs 对象。

#!/usr/bin/env node require('shelljs/global'); var argv = require('yargs') .command("morning", "good morning", function (yargs) { echo("Good Morning"); var argv = yargs.reset() .option("m", { alias: "message", description: "provide any sentence" }) .help("h") .alias("h", "help") .argv; echo(argv.m); }) .argv; 

用法如下。

$ hello morning -m "Are you hungry?" Good Morning
Are you hungry?

转自:http://www.ruanyifeng.com/blog/2015/05/command-line-with-node.html

MySQL命令行参数整理

 mysql  MySQL命令行参数整理已关闭评论
11月 102015
 

Mysql命令行参数整理:

—help,-? 
显示帮助消息并退出。


–batch,-B 
打印结果,使用tab作为列间隔符,每个行占用新的一行。使用该选项,则mysql不使用历史文件。


–character-sets -dir=path 
字符集的安装目录。


–compress,-C 
压缩在客户端和服务器之间发送的所有信息(如果二者均支持压缩)。


—database=db_name,-D db_name 
要使用的数据库教程。主要在选项文件中有用。


—debug[=debug_options],-# [debug_options] 
写调试日志。debug_options字符串通常为’d:t:o,file_name’。 默认为’d:t:o,/tmp/mysql.trace’。


—debug-info,-T 
当程序退出时输出部分调试信息。


–default-character-set=charset 
使用charsetas作为默认字符集。


–execute=statement, -e statement 
执行语句并退出。默认输出格式与用–batch产生的相同。


–force,-f 
即使出现一个SQL错误仍继续。


–host=host_name,-h host_name 
连接给定主机上的MySQL服务器。


–html,-H 
产生HTML输出。


–ignore-space,-i 
忽视函数名后面的空格


–local-infile[={0|1}] 
为LOAD DATA INFILE启用或禁用LOCAL功能。没有值,该选项启用LOCAL。还可以采用–local-infile=0或–local-infile=1以显式禁用或启用LOCAL。如果服务器不支持,启用LOCAL不会生效。


–named-commands,-G 
命名的命令被启用。允许长格式命令和短格式*命令。例如,quit和q均被识别。


–no-auto-rehash,-A 
不自动重新进行哈希运算。该选项使mysql启动得更快,但果你想要完成表和列名,你必须发出rehash命令。


–no-beep,-b 
当发生错误时不要发出报警声。


–no-named-commands,-g 
命名的命令被禁用。只使用*形式,或者只使用行开头的命名用分号(‘;’)结束的的命令。对于MySQL 3.23.22,默认情况mysql启动时启用该选项。然而,即使使用该选项,长格式命令仍然从第1行工作。


–no-pager 
不使用分页器来显示查询输出。


–no-tee 
不将输出复制到文件中。 
· 
–one–database,-O 
忽视除了为命令行中命名的默认数据库的语句。可以帮助跳过对二进制日志中的其它数据库的更新。

 

–pager[=command] 
使用给出的命令来分页查询输出。如果该命令被删除,默认分页器为PAGER环境变量的值。合法pagers是less、more、cat [>filename]等等。该选项只在Unix中工作。不能以批处理模式工作


–password[=password],-p[password] 
当连接服务器时使用的密码。如果使用短选项形式(-p),选项和 密码之间不能有空格。如果在命令行中–password或-p选项后面没有 密码值,则提示输入一个密码。在SysV-based UNIX系统中应省略密码,因为密码可以显示在ps教程的输出中。


–port=port_num,-P port_num 
用于连接的TCP/IP端口号。


–prompt=format_str 
将提示设置为指定的格式。默认为mysql>。


–protocol={TCP | SOCKET | PIPE | MEMORY} 
使用的连接协议。


–quick,-q 
不缓存每个查询的结果,按照接收顺序打印每一行。如果输出被挂起,服务器会慢下来。使用该选项,mysql不使用历史文件。


–raw,-r 
写列的值而不转义转换。通常结合–batch选项使用。


–reconnect 
如果与服务器之间的连接断开,自动尝试重新连接。每次连接断开后则尝试一次重新连接。要想禁止重新连接,使用–skip-reconnect。


–safe-updates,–i-am-a-dummy,-U 
只允许那些使用键值指定行生效的UPDATE和DELETE语句。如果已经在选项文件中设置了该选项,可以用命令行中的–safe-updates覆盖它。


–secure-auth 
不向旧(pre-4.1.1)格式的服务器发送密码。这样可以防止不使用新密码格式的服务器的连接。


–show-warnings 
如果每个语句后有警告则显示。该选项适用于交互式和批处理模式。


–sigint-ignore 
忽视SIGINT符号(一般为Control-C的结果)。


–silent,-s 
沉默模式。产生少的输出。可以多次使用该选项以产生更少的输出。


–skip-column-names,-N 
在结果中不写列名。


–skip-line-numbers,-L 
在错误信息中不写行号。当你想要比较包括错误消息的结果文件时有用。


–socket=path,-S path 
用于连接的套接字文件。


–tables,-t 
用表格式显示输出。这是交互式应用的默认设置,但可用来以批处理模式产生表输出。


–tee=file_name 
将输出拷贝添加到给定的文件中。该选项在批处理模式不工作。


–unbuffered,-n 
每次查询后刷新缓存区。


–user=user_name,-u user_name 
当连接服务器时MySQL使用的用户名。


–verbose,-v 
冗长模式。产生更多的输出。可以多次使用该选项以产生更多的输出。(例如,-v -v -v甚至可以在批处理模式产生表输出格式)。

 

–version,-V 
显示版本信息并退出。


–vertical,-E 
垂直输出查询输出的行。没有该选项,可以用G结尾来指定单个语句的垂直输出。


–wait,-w 
如果不能建立连接,等待并重试而不是放弃。


–xml,-X 
产生XML输出。 
你还可以使用–var_name=value选项设置下面的变量:


connect_timeout 
连接超时前的秒数。(默认值是0)。

 

max_allowed_packet 
从服务器发送或接收的最大包长度。(默认值是16MB)。

 

max_join_size 
当使用–safe-updates时联接中的行的自动限制。(默认值是1,000,000)。

 

net_buffer_length 
TCP/IP和套接字通信缓冲区大小。(默认值是16KB)。

 

select_limit 
当使用–safe-updates时SELECT语句的自动限制。(默认值是1,000)。 
也可以使用–set-variable=var_name=value or -O var_name=value语法来设置变量。不赞成使用[i]该语法[/i]。

HttpClient使用Post和Get提交参数

 java  HttpClient使用Post和Get提交参数已关闭评论
5月 042015
 
 
如果PostMethod提交的是中文字符,需要加上相应的编码格式:  post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");  
如果GetMethod提交的参数有中文字符,需要先转换成utf-8格式:  URLEncoder.encode("中文", "utf-8"); 
测试代码如下:
package httpclient;

import java.io.IOException;
import java.net.URLEncoder;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class HttpClientTest {

	public static void main(String[] args) throws Exception{
		String url = "/xx.jsp/xxxx";
		String host = "www.xxx.cn";
		String param = "city="+URLEncoder.encode("测试", "utf-8")+"&userID=";
		HttpClient httpClient = new HttpClient();
		httpClient.getHostConfiguration().setHost(host, 80, "http");

		HttpMethod method = getMethod(url, param);
		//HttpMethod method = postMethod(url);

		httpClient.executeMethod(method);

		String response = method.getResponseBodyAsString();
		//String response = new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"));
		System.out.println(response);
	}

	private static HttpMethod getMethod(String url,String param) throws IOException{
		GetMethod get = new GetMethod(url+"?"+param);
		get.releaseConnection();
		return get;
	}

	private static HttpMethod postMethod(String url) throws IOException{
		PostMethod post = new PostMethod(url);
		post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); 
		NameValuePair[] param = { new NameValuePair("city","测试"),
				new NameValuePair("userID","")} ;
    	        post.setRequestBody(param);
    	        post.releaseConnection();
		return post;
	}
}

Spring Aop Advise方法(增强方法) 中获取目标方法的参数

 spring  Spring Aop Advise方法(增强方法) 中获取目标方法的参数已关闭评论
10月 272014
 

非常好的一篇文章,学习了:http://jackyin5918.iteye.com/blog/1918076

Spring Aop Advise方法(增强方法) 中获取目标方法的参数

 

1. 概念 

   

   切面类: 一种特殊bean,通过aop配置,其中的方法(增强方法),会对目标bean的目标方法做一些增强处理

   (比如在目标方法之前或之后调用等).

   

   切入点(pointcut): 一种规则,普通bean中符合这种规则的方法,将成为上面切面类中所说的目标方法,接受切面类方法

   的特殊处理.

   

   增强方法(Advice),包括aop:befor,aop:after,aop:after-retuing,aop:around,aop:throwing等.

   

2. 配置片段:

     

Xml代码  收藏代码

  1. <!– AOP测试的chinese –>  
  2.             <bean id=“chinese_aop” class=“test.aop.Chinese” />  
  3.             <!– 定义一个普通bean,作为切面bean –>  
  4.             <bean id=“accessArgAspect” class=“test.aop.aspect.AccessArgAspect” />  
  5.             <!– AOP配置  –>   
  6.             <aop:config>  
  7.               <!– 配置切面aspect –>  
  8.               <aop:aspect id=“aspect” ref=“accessArgAspect”>  
  9.                 <aop:after-returning   
  10.                   pointcut=“execution(* test.aop.*.*(..))”   
  11.                   method=“access”  
  12.                   returning=“retval”  
  13.                   arg-names=“time,food,retval”   
  14.                 />  
  15.               </aop:aspect>   
  16.             </aop:config>  
Xml代码  收藏代码

  1. <!– AOP测试的chinese –>  
  2.             <bean id=“chinese_aop” class=“test.aop.Chinese” />  
  3.             <!– 定义一个普通bean,作为切面bean –>  
  4.             <bean id=“accessArgAspect” class=“test.aop.aspect.AccessArgAspect” />  
  5.             <!– AOP配置  –>   
  6.             <aop:config>  
  7.               <!– 配置切面aspect –>  
  8.               <aop:aspect id=“aspect” ref=“accessArgAspect”>  
  9.                 <aop:after-returning   
  10.                   pointcut=“execution(* test.aop.*.*(..))”   
  11.                   method=“access”  
  12.                   returning=“retval”  
  13.                   arg-names=“time,food,retval”   
  14.                 />  
  15.               </aop:aspect>   
  16.             </aop:config>  

       

    上面的配置中:

    <bean id=”chinese_aop” class=”test.aop.Chinese” />

    配置了普通的bean,该bean中的一些方法

    即将满足切入点配置规则,接受切面类中增强方法(Advice)的增强处理.

    

    <bean id=”accessArgAspect” class=”test.aop.aspect.AccessArgAspect” /> 定义一个切面类,

    切面类可以是一个普通的bean.

    

    <aop:config>

      <!–配置切面aspect,通过ref关联到前面配置的作为切面类的bean–>

      <aop:aspect id=”aspect” ref=”accessArgAspect”>

        <!– 配置一种aop:after-returning增强处理–>

        <aop:after-returning

          <!– 切入点 规则,符合这个规则的普通bean中的方法将接受增强处理 –>

          pointcut=”execution(*test.aop.*.*(..)) and args(food,time,..)”  

          <!– 切面类中,作为增强处理的方法的名称 –>

          method=”access”

          <!– 普通bean,接受增强处理方法的返回值,void的类型被视为null –> 

          returning=”retval” 

          <!– 切面类中增强方法的参数名,这个配置可以省略 –>

          arg-names=”time,food,retval”

        />

        

      </aop:aspect>

    </aop:config>

    

3. 参数绑定

   切面类 方法(增强方法)获取 目标方法(普通bean中接受增强方法处理的方法) 参数的方式称为参数绑定.

   

   (1) 增强方法 不需要传递参数,则不需要参数绑定.

   

   (2) 增强方法中,只有一个JoinPoint类型的参数,使用这种参数,也不需要参数绑定.

       因为, JoinPoint类有一些方法可以获取目标方法的调用信息(包括参数信息),比如:

       Object[] getArgs(),返回在执行目标方法时传递的参数

       Signature getSignature(),获取 目标方法的签名

       Object getTarget():返回被植入 增强处理的目标对象

       Object getThis(): 返回AOP框架为目标对象生成的代理对象(Spring AOP通过动态代理实现)

       

       假如是aop:around类型的增强处理方法,可以使用ProceedingJoinPoint作为参数,

       ProceedingJoinPoint除了有上述的几个方法外,还有一个proceed()方法,替代目标方法执行.

       

   (3) 增强方法中,有普通类型的参数,

       比如public void access(Date time,String food, String retval)

       这种增强方法,必须要在pointcut中通过配置args 和 returning,保证参数正确绑定.

       (returning只针对aop:after-returning类型的增强处理,其他的可以省略)

       (即,增强方法中出现的参数名必须在pointcut配置中都得到明确的配置,否则报异常)

       pointcut=”execution(*test.aop.*.*(..)) and args(food,time,..)”

       中args(food,time,..)中的food和time是参数名,来自切面类的增强方法,不能乱写,

       必须和切面类中增强方法的参数名称一致,在切面类的增强方法参数列表中必须能找到.

       因为在增强方法public void access(Date time,String food, String retval)中,time是Date类型的,

       food是String类型的,所以pointcut(切入点)定义中and args(food,time,..)符合and前面的规则的同时

       还要符合args(food,time,..)的规则.

       args(food,time,..)表是所有 第一个参数是String类型,第二个参数是Date类型的方法才能称为目标方法.

       .. 表示可以有第三个,第四个, … , 第n个参数,但是至少有两个参数(String,Date)

       所以需要注意的有:

       a. 切面类中的增强方法参数,必须要在pointcut中有明确指定,比如

          public void access(Date time,String food, String retval)

          这个方法中三个参数food,和time通过args指定了,retval表示aop:after-returning定义的目标函数的返回值.

       b. 明确指定了参数后,AOP框架在运行时能正确绑定参数,因为:

          and args(food,time,..)表示 只对一类目标方法的调用做增强处理,这种目标方法是:在准备调用这种目标方法时,

          实际传递给它的参数为food和time所表示的类型(food和time必须在增强方法的参数列表中找到,这样就根据增强方法确定了food和time的类型).

          并且,传递参数的顺序也要是和args(food,time,..)中一致.这样在调用目标方法时,至少会按顺序传递food,time两个参数,

          AOP框架可以将这两个参数传递给 增强方法.

   

   (4) 增强方法中 有 JoinPoint和普通类型参数,

       则必须将JoinPoint类型的参数作为第一个参数,普通参数从第二个开始.

       其他的处理方式,按照上面(3)中仅含有普通参数的方式处理.

       

 主要代码;

Java代码  收藏代码

  1. package test.aop;  
  2.   
  3. import java.util.Date;  
  4.   
  5. /** 
  6.  *  
  7.  * 普通bean的接口 
  8.  * 
  9.  */  
  10. public interface Person  
  11. {  
  12.   String sayHello(String name);  
  13.   void eat(String food, Date time);  
  14.   void eat2(String food, Date time,String test);  
  15. }  
Java代码  收藏代码

  1. package test.aop;  
  2.   
  3. import java.util.Date;  
  4.   
  5. /** 
  6.  *  
  7.  * 普通bean的接口 
  8.  * 
  9.  */  
  10. public interface Person  
  11. {  
  12.   String sayHello(String name);  
  13.   void eat(String food, Date time);  
  14.   void eat2(String food, Date time,String test);  
  15. }  

 

Java代码  收藏代码

  1. package test.aop;  
  2.   
  3. import java.util.Date;  
  4.   
  5. /** 
  6.  *  
  7.  *一个普通bean,eat方法和sayHello方法,是需要被切入,动态影响的 
  8.  * 
  9.  */  
  10. public class Chinese implements Person  
  11. {  
  12.   
  13.   @Override  
  14.   public void eat(String afood, Date atime)  
  15.   {  
  16.     System.out.println(“正在吃: “ + afood + “, 时间是: “ + atime);  
  17.   }  
  18.   
  19.   @Override  
  20.   public String sayHello(String name)  
  21.   {  
  22.     return name + ” Hello, Spring AOP.”;  
  23.   }  
  24.     
  25.   public void eat2(String afood, Date atime,String test)  
  26.   {  
  27.     System.out.println(“eat2 ——— 正在吃: “ + afood + “, 时间是: “ + atime + “, eat2里面的test= “ + test);  
  28.   }  
  29.   
  30. }  
Java代码  收藏代码

  1. package test.aop;  
  2.   
  3. import java.util.Date;  
  4.   
  5. /** 
  6.  *  
  7.  *一个普通bean,eat方法和sayHello方法,是需要被切入,动态影响的 
  8.  * 
  9.  */  
  10. public class Chinese implements Person  
  11. {  
  12.   
  13.   @Override  
  14.   public void eat(String afood, Date atime)  
  15.   {  
  16.     System.out.println(“正在吃: “ + afood + “, 时间是: “ + atime);  
  17.   }  
  18.   
  19.   @Override  
  20.   public String sayHello(String name)  
  21.   {  
  22.     return name + ” Hello, Spring AOP.”;  
  23.   }  
  24.     
  25.   public void eat2(String afood, Date atime,String test)  
  26.   {  
  27.     System.out.println(“eat2 ——— 正在吃: “ + afood + “, 时间是: “ + atime + “, eat2里面的test= “ + test);  
  28.   }  
  29.   
  30. }  

 

Java代码  收藏代码

  1. package test.aop.aspect;  
  2.   
  3. import java.util.Arrays;  
  4. import java.util.Date;  
  5.   
  6. import org.aspectj.lang.JoinPoint;  
  7.   
  8. /** 
  9.  *  
  10.  * 定义切面类,处理test.aop.Chinese.eat() 
  11.  * 
  12.  */  
  13. public class AccessArgAspect  
  14. {  
  15.     
  16.   //普通的 增强方法  
  17.   public void access(Date time,String food, String retval)  
  18.   {  
  19.     System.out.println(“”);  
  20.       
  21.     System.out.println(“目标方法中 String 参数为: “ + food);  
  22.     System.out.println(“目标方法中 String 参数为: “ + time);  
  23.     System.out.println(“目标方法 返回值: “ + retval);  
  24.       
  25.     System.out.println(“模拟记录日志…”);  
  26.       
  27.   }  
  28.     
  29.   /** 
  30.    * 第一个参数为JoinPoint类型的增强方法,JoinPoint必须为第一个参数 
  31.    * @param jp 
  32.    * @param time 
  33.    * @param food 
  34.    * @param retval 
  35.    */  
  36.   public void accessWithJoinPoint(JoinPoint jp,Date time,String food)  
  37.   {  
  38.     System.out.println(“”);  
  39.     System.out.println(“JoinPoint.getArgs()获取参数列表:” + Arrays.toString(jp.getArgs()));  
  40.       
  41.     System.out.println(“JoinPoint jp —- 目标方法中 String 参数为: “ + food);  
  42.     System.out.println(“JoinPoint jp —- 目标方法中 String 参数为: “ + time);  
  43.       
  44.     System.out.println(“JoinPoint jp —- 模拟记录日志…”);  
  45.       
  46.   }  
  47. }  
Java代码  收藏代码

  1. package test.aop.aspect;  
  2.   
  3. import java.util.Arrays;  
  4. import java.util.Date;  
  5.   
  6. import org.aspectj.lang.JoinPoint;  
  7.   
  8. /** 
  9.  *  
  10.  * 定义切面类,处理test.aop.Chinese.eat() 
  11.  * 
  12.  */  
  13. public class AccessArgAspect  
  14. {  
  15.     
  16.   //普通的 增强方法  
  17.   public void access(Date time,String food, String retval)  
  18.   {  
  19.     System.out.println(“”);  
  20.       
  21.     System.out.println(“目标方法中 String 参数为: “ + food);  
  22.     System.out.println(“目标方法中 String 参数为: “ + time);  
  23.     System.out.println(“目标方法 返回值: “ + retval);  
  24.       
  25.     System.out.println(“模拟记录日志…”);  
  26.       
  27.   }  
  28.     
  29.   /** 
  30.    * 第一个参数为JoinPoint类型的增强方法,JoinPoint必须为第一个参数 
  31.    * @param jp 
  32.    * @param time 
  33.    * @param food 
  34.    * @param retval 
  35.    */  
  36.   public void accessWithJoinPoint(JoinPoint jp,Date time,String food)  
  37.   {  
  38.     System.out.println(“”);  
  39.     System.out.println(“JoinPoint.getArgs()获取参数列表:” + Arrays.toString(jp.getArgs()));  
  40.       
  41.     System.out.println(“JoinPoint jp —- 目标方法中 String 参数为: “ + food);  
  42.     System.out.println(“JoinPoint jp —- 目标方法中 String 参数为: “ + time);  
  43.       
  44.     System.out.println(“JoinPoint jp —- 模拟记录日志…”);  
  45.       
  46.   }  
  47. }  

 

Java代码  收藏代码

  1. package test.aop;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import org.springframework.context.ApplicationContext;  
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7.   
  8. /** 
  9.  *  
  10.  * AOP客户端测试类 
  11.  * 
  12.  */  
  13. public class TestClient  
  14. {  
  15.   public static void main(String[] args)  
  16.   {  
  17.     ApplicationContext ctx = new ClassPathXmlApplicationContext(“bean.xml”);  
  18.     System.out.println(ctx);  
  19.       
  20.     Person person = ctx.getBean(“chinese_aop”,Person.class);  
  21.       
  22.     person.sayHello(“jack”);  
  23.       
  24.     person.eat(“米饭”,new Date());  
  25.       
  26.     person.eat2(“米饭”,new Date(),“test”);  
  27.   }  
  28. }  
Java代码  收藏代码

  1. package test.aop;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import org.springframework.context.ApplicationContext;  
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7.   
  8. /** 
  9.  *  
  10.  * AOP客户端测试类 
  11.  * 
  12.  */  
  13. public class TestClient  
  14. {  
  15.   public static void main(String[] args)  
  16.   {  
  17.     ApplicationContext ctx = new ClassPathXmlApplicationContext(“bean.xml”);  
  18.     System.out.println(ctx);  
  19.       
  20.     Person person = ctx.getBean(“chinese_aop”,Person.class);  
  21.       
  22.     person.sayHello(“jack”);  
  23.       
  24.     person.eat(“米饭”,new Date());  
  25.       
  26.     person.eat2(“米饭”,new Date(),“test”);  
  27.   }  
  28. }  

 

Xml代码  收藏代码

  1. <?xml version=“1.0” encoding=“UTF-8”?>    
  2. <beans xmlns=“http://www.springframework.org/schema/beans”    
  3.         xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”    
  4.         xmlns:aop=“http://www.springframework.org/schema/aop”  
  5.         xsi:schemaLocation=”http://www.springframework.org/schema/beans    
  6.             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.             http://www.springframework.org/schema/aop   
  8.             http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  9.             http://www.springframework.org/schema/tx   
  10.             http://www.springframework.org/schema/tx/spring-tx-3.0.xsd”>   
  11.               
  12.             <!– 小试牛刀 property使用 name,value–>  
  13.             <bean id=“personService” class=“test.spring.PersonService”>  
  14.               <property name=“name” value=“wawa”></property>  
  15.             </bean>  
  16.               
  17.             <!–   
  18.                   设值注入  
  19.                 property使用 name,ref ,  
  20.                 ref也是一个bean的id,ref 可以在stoneAxe和steelAxe之间随意切换,而不用修改java代码   
  21.             —>  
  22.             <bean id=“chinese” class=“test.ioc.setter.Chinese”>  
  23.               <property name=“axe” ref=“steelAxe”></property>  
  24.             </bean>  
  25.             <bean id=“stoneAxe” class=“test.ioc.setter.StoneAxe” />   
  26.             <bean id=“steelAxe” class=“test.ioc.setter.SteelAxe” />   
  27.               
  28.             <!–   
  29.                 构造注入  
  30.                 constructor-arg标签,ref ,  
  31.                 ref也是一个bean的id,ref 可以在stoneAxe和steelAxe之间随意切换,而不用修改java代码  
  32.                 constructor-arg 也可以配置value,表示传递给构造函数的是一个 普通的值,而不是另一个bean   
  33.             —>  
  34.             <bean id=“chinese1” class=“test.ioc.constructor.Chinese”>  
  35.               <constructor-arg ref=“steelAxe” />   
  36.             </bean>  
  37.               
  38.             <!– 国际化 –>  
  39.            <bean id=“messageSource” class=“org.springframework.context.support.ResourceBundleMessageSource”>  
  40.               <property name=“basenames” >  
  41.                 <list>  
  42.                   <!– 这里的value可带路径   –>  
  43.                   <value>message</value>  
  44.                 </list>  
  45.               </property>   
  46.             </bean>  
  47.               
  48.             <!–   
  49.               ApplicationContext的事件机制   
  50.                 在Spring中配置了实现ApplicationListener接口的Bean,  
  51.               Spring容器就会把这个Bean当成容器事件的监听器  
  52.             —>  
  53.             <bean class=“test.springevent.EmainNotifier” />   
  54.               
  55.             <!– bean中获取 ApplicationContext引用–>  
  56.             <bean name=“beangetappcontext” class=“test.bean.get.appcontext.BeanGetAppContext” />  
  57.               
  58.             <!– AOP测试的chinese –>  
  59.             <bean id=“chinese_aop” class=“test.aop.Chinese” />  
  60.             <!– 定义一个普通bean,作为切面bean –>  
  61.             <bean id=“accessArgAspect” class=“test.aop.aspect.AccessArgAspect” />  
  62.             <!– AOP配置  –>   
  63.             <aop:config>  
  64.               <!– 配置切面aspect –>  
  65.               <aop:aspect id=“aspect” ref=“accessArgAspect”>  
  66.                 <aop:after-returning   
  67.                   pointcut=“execution(* test.aop.*.*(..)) and args(food,time,..)”   
  68.                   method=“access”  
  69.                   returning=“retval”  
  70.                   arg-names=“time,food,retval”   
  71.                 />  
  72.                   
  73.                 <aop:before   
  74.                   pointcut=“execution(* test.aop.*.*(..)) and args(food,time,..)”   
  75.                   method=“accessWithJoinPoint”  
  76.                 />  
  77.                   
  78.               </aop:aspect>   
  79.             </aop:config>  
  80.                
  81. </beans>   
Xml代码  收藏代码

  1. <?xml version=“1.0” encoding=“UTF-8”?>    
  2. <beans xmlns=“http://www.springframework.org/schema/beans”    
  3.         xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”    
  4.         xmlns:aop=“http://www.springframework.org/schema/aop”  
  5.         xsi:schemaLocation=”http://www.springframework.org/schema/beans    
  6.             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.             http://www.springframework.org/schema/aop   
  8.             http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  9.             http://www.springframework.org/schema/tx   
  10.             http://www.springframework.org/schema/tx/spring-tx-3.0.xsd”>   
  11.               
  12.             <!– 小试牛刀 property使用 name,value–>  
  13.             <bean id=“personService” class=“test.spring.PersonService”>  
  14.               <property name=“name” value=“wawa”></property>  
  15.             </bean>  
  16.               
  17.             <!–   
  18.                   设值注入  
  19.                 property使用 name,ref ,  
  20.                 ref也是一个bean的id,ref 可以在stoneAxe和steelAxe之间随意切换,而不用修改java代码   
  21.             —>  
  22.             <bean id=“chinese” class=“test.ioc.setter.Chinese”>  
  23.               <property name=“axe” ref=“steelAxe”></property>  
  24.             </bean>  
  25.             <bean id=“stoneAxe” class=“test.ioc.setter.StoneAxe” />   
  26.             <bean id=“steelAxe” class=“test.ioc.setter.SteelAxe” />   
  27.               
  28.             <!–   
  29.                 构造注入  
  30.                 constructor-arg标签,ref ,  
  31.                 ref也是一个bean的id,ref 可以在stoneAxe和steelAxe之间随意切换,而不用修改java代码  
  32.                 constructor-arg 也可以配置value,表示传递给构造函数的是一个 普通的值,而不是另一个bean   
  33.             —>  
  34.             <bean id=“chinese1” class=“test.ioc.constructor.Chinese”>  
  35.               <constructor-arg ref=“steelAxe” />   
  36.             </bean>  
  37.               
  38.             <!– 国际化 –>  
  39.            <bean id=“messageSource” class=“org.springframework.context.support.ResourceBundleMessageSource”>  
  40.               <property name=“basenames” >  
  41.                 <list>  
  42.                   <!– 这里的value可带路径   –>  
  43.                   <value>message</value>  
  44.                 </list>  
  45.               </property>   
  46.             </bean>  
  47.               
  48.             <!–   
  49.               ApplicationContext的事件机制   
  50.                 在Spring中配置了实现ApplicationListener接口的Bean,  
  51.               Spring容器就会把这个Bean当成容器事件的监听器  
  52.             —>  
  53.             <bean class=“test.springevent.EmainNotifier” />   
  54.               
  55.             <!– bean中获取 ApplicationContext引用–>  
  56.             <bean name=“beangetappcontext” class=“test.bean.get.appcontext.BeanGetAppContext” />  
  57.               
  58.             <!– AOP测试的chinese –>  
  59.             <bean id=“chinese_aop” class=“test.aop.Chinese” />  
  60.             <!– 定义一个普通bean,作为切面bean –>  
  61.             <bean id=“accessArgAspect” class=“test.aop.aspect.AccessArgAspect” />  
  62.             <!– AOP配置  –>   
  63.             <aop:config>  
  64.               <!– 配置切面aspect –>  
  65.               <aop:aspect id=“aspect” ref=“accessArgAspect”>  
  66.                 <aop:after-returning   
  67.                   pointcut=“execution(* test.aop.*.*(..)) and args(food,time,..)”   
  68.                   method=“access”  
  69.                   returning=“retval”  
  70.                   arg-names=“time,food,retval”   
  71.                 />  
  72.                   
  73.                 <aop:before   
  74.                   pointcut=“execution(* test.aop.*.*(..)) and args(food,time,..)”   
  75.                   method=“accessWithJoinPoint”  
  76.                 />  
  77.                   
  78.               </aop:aspect>   
  79.             </aop:config>  
  80.                
  81. </beans>   

 

工程文件注:

 

使用Spring 3.2.0的所有ja包,

3.2.0的srping包,做AOP需要依赖(Spring 3.2.0中去除了依赖包,需要自己找)

com.springsource.org.aopalliance-1.0.0.jar,下载地址http://ebr.springsource.com/repository/app/bundle/version/detail?name=org.springframework.aop&version=3.2.0.RELEASE

还有,3.0.2的com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar包,

下载3.0.2版本的依赖包以后,找

spring-framework-3.0.2.RELEASE-dependencies (1)org.aspectjcom.springsource.org.aspectj.weaver1.6.8.RELEASE这个目录里面有  

python 函数 参数的传递 (带星号说明)

 python  python 函数 参数的传递 (带星号说明)已关闭评论
7月 012013
 

转自:http://www.51testing.com/?uid-88300-action-viewspace-itemid-102923

python中函数参数的传递是通过赋值来传递的。函数参数的使用又有俩个方面值得注意:1.函数参数是如何定义的 2.在调用函数的过程中参数是如何被解析

先看第一个问题,在python中函数参数的定义主要有四种方式:

1.F(arg1,arg2,…)

这是最常见的定义方式,一个函数可以定义任意个参数,每个参数间用逗号分割,用这种方式定义的函数在调用的的时候也必须在函数名后的小括号里提供个数相等的值(实际参数),而且顺序必须相同,也就是说在这种调用方式中,形参和实参的个数必须一致,而且必须一一对应,也就是说第一个形参对应这第一个实参。例如:

def a(x,y):

    print x,y

调用该函数,a(1,2)则x取1,y取2,形参与实参相对应,如果a(1)或者a(1,2,3)则会报错。



2.F(arg1,arg2=value2,…)

这种方式就是第一种的改进版,提供了默认值

def a(x,y=3):

    print x,y

调用该函数,a(1,2)同样还是x取1,y取2,但是如果a(1),则不会报错了,这个时候x还是1,y则为默认的3。上面这俩种方式,还可以更换参数位置,比如a(y=8,x=3)用这种形式也是可以的。



3.F(*arg1)

上面俩个方式是有多少个形参,就传进去多少个实参,但有时候会不确定有多少个参数,则此时第三种方式就比较有用,它以一个*加上形参名的方式来表示这个函数的实参个数不定,可能为0个也可能为n个。注意一点是,不管有多少个,在函数内部都被存放在以形参名为标识符的tuple中。

>>> def a(*x):

if len(x)==0:

   print 'None'

else:

   print x

>>> a(1)

(1,)        #存放在元组中

>>> a()

None

>>> a(1,2,3)

(1, 2, 3)

>>> a(m=1,y=2,z=3)

Traceback (most recent call last):

File "<pyshell#16>", line 1, in -toplevel-

    a(m=1,y=2,z=3)

TypeError: a() got an unexpected keyword argument 'm'



4.F(**arg1)

形参名前加俩个*表示,参数在函数内部将被存放在以形式名为标识符的dictionary中,这时调用函数的方法则需要采用arg1=value1,arg2=value2这样的形式。

>>> def a(**x):

if len(x)==0:

   print 'None'

else:

   print x  

>>> a()

None

>>> a(x=1,y=2)

{'y': 2, 'x': 1}      #存放在字典中

>>> a(1,2)            #这种调用则报错

Traceback (most recent call last):

File "<pyshell#25>", line 1, in -toplevel-

    a(1,2)

TypeError: a() takes exactly 0 arguments (2 given)



上面介绍了四种定义方式,接下来看函数参数在调用过程中是怎么被解析的,其实只要记住上面这四种方法优先级依次降低,先1,后2,再3,最后4,也就是先把方式1中的arg解析,然后解析方式2中的arg=value,再解析方式3,即是把多出来的arg这种形式的实参组成个tuple传进去,最后把剩下的key=value这种形式的实参组成一个dictionary传给带俩个星号的形参,也就方式4

>>> def test(x,y=1,*a,**b):

print x,y,a,b



>>> test(1)

1 1 () {}

>>> test(1,2)

1 2 () {}

>>> test(1,2,3)

1 2 (3,) {}

>>> test(1,2,3,4)

1 2 (3, 4) {}

>>> test(x=1,y=2)

1 2 () {}

>>> test(1,a=2)

1 1 () {'a': 2}

>>> test(1,2,3,a=4)

1 2 (3,) {'a': 4}

>>> test(1,2,3,y=4)

Traceback (most recent call last):

File "<pyshell#52>", line 1, in -toplevel-

    test(1,2,3,y=4)

TypeError: test() got multiple values for keyword argument 'y'

Python 参数知识

 python  Python 参数知识已关闭评论
5月 302013
 

转自:http://blog.csdn.net/qinyilang/article/details/5484415

过量的参数

在运行时知道一个函数有什么参数,通常是不可能的。另一个情况是一个函数能操作很多对象。更有甚者,调用自身的函数变成一种api提供给可用的应用。



对于这些情况,python提供了两种特别的方法来定义函数的参数,允许函数接受过量的参数,不用显式声明参数。这些“额外”的参数下一步再解释。



注意args和kwargs只是python的约定。任何函数参数,你可以自己喜欢的方式命名,但是最好和python标准的惯用法一致,以便你的代码,其他的程序员也能轻松读懂。


位置参数



在参数名之前使用一个星号,就是让函数接受任意多的位置参数。

>>> def multiply(*args):
…     total = 1
…     for arg in args:
…         total *= arg
…     return total

>>> multiply(2, 3)
6
>>> multiply(2, 3, 4, 5, 6)
720

python把参数收集到一个元组中,作为变量args。显式声明的参数之外如果没有位置参数,这个参数就作为一个空元组。

关键字参数

python在参数名之前使用2个星号来支持任意多的关键字参数。

>>> def accept(**kwargs):
…     for keyword, value in kwargs.items():
…         print "%s => %r" % (keyword, value)

>>> accept(foo='bar', spam='eggs')
foo => 'bar'
spam => 'eggs'

注意:kwargs是一个正常的python字典类型,包含参数名和值。如果没有更多的关键字参数,kwargs就是一个空字典。

混合参数类型

任意的位置参数和关键字参数可以和其他标准的参数声明一起使用。混合使用时要加些小心,因为python中他们的次序是重要的。参数归为4类,不是所有的类别都需要。他们必须按下面的次序定义,不用的可以跳过。

1)必须的参数
2)可选的参数
3)过量的位置参数
4)过量的关键字参数

def complex_function(a, b=None, *c, **d):

这个次序是必须的,因为*args和**kwargs只接受那些没有放进来的其他任何参数。没有这个次序,当你调用一个带有位置参数的函数,python就不知道哪个值是已声明参数想要的,也不知道哪个被作为过量参数对待。

也要注意的是,当函数能接受许多必须的参数和可选的参数,那它只要定义一个过量的参数类型即可。

传递参数集合

除了函数能接受任意参数集合,python代码也可以调用带有任意多数量的函数,像前面说过的用星号。这种方式传递的参数由python扩展成为参数列表。以便被调用的函数
不需要为了这样调用而去使用过量参数。python中任何可调用的,都能用这种技法来调用。并且用相同的次序规则和标准参数一起使用。

>>> def add(a, b, c):
…     return a + b + c

>>> add(1, 2, 3)
6
>>> add(a=4, b=5, c=6)
15
>>> args = (2, 3)
>>> add(1, *args)
6
>>> kwargs={'b': 8, 'c': 9}
>>> add(a=7, **kwargs)
24
>>> add(a=7, *args)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() got multiple values for keyword argument 'a'
>>> add(1, 2, a=7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() got multiple values for keyword argument 'a'

注意这个例子的最后几行,特别留意当传递一个元组作为过量的位置参数时,是否要显式的传递关键字参数。因为python使用次序规则来扩展过量的参数,那位置参数要放在前面。这个例子中,最后两个调用是相同的,python不能决定那个值是给a的。

 Posted by at 下午3:03  Tagged with:

Java虚拟机(JVM)参数(-X,-XX)配置说明

 java  Java虚拟机(JVM)参数(-X,-XX)配置说明已关闭评论
4月 142013
 
在Java、J2EE大型应用中,JVM非标准参数的配置直接关系到整个系统的性能。
JVM非标准参数指的是JVM底层的一些配置参数,这些参数在一般开发中默认即可,不需要任何配置。但是在生产环境中,为了提高性能,往往需要调整这些参数,以求系统达到最佳新能。
另外这些参数的配置也是影响系统稳定性的一个重要因素,相信大多数Java开发人员都见过“OutOfMemory”类型的错误。呵呵,这其中很可能就是JVM参数配置不当或者就没有配置没意识到配置引起的。
 
为了说明这些参数,还需要说说JDK中的命令行工具一些知识做铺垫。
 
首先看如何获取这些命令配置信息说明:
假设你是windows平台,你安装了J2SDK,那么现在你从cmd控制台窗口进入J2SDK安装目录下的bin目录,然后运行java命令,出现如下结果,这些就是包括java.exe工具的和JVM的所有命令都在里面。
 
———————————————————————–
D:j2sdk15bin>java
Usage: java [-options] class [args…]
           (to execute a class)
   or  java [-options] -jar jarfile [args…]
           (to execute a jar file)
 
where options include:
    -client       to select the “client” VM
    -server       to select the “server” VM
    -hotspot      is a synonym for the “client” VM  [deprecated]
                  The default VM is client.
 
    -cp <class search path of directories and zip/jar files>
    -classpath <class search path of directories and zip/jar files>
                  A ; separated list of directories, JAR archives,
                  and ZIP archives to search for class files.
    -D<name>=<value>
                  set a system property
    -verbose[:class|gc|jni]
                  enable verbose output
    -version      print product version and exit
    -version:<value>
                  require the specified version to run
    -showversion  print product version and continue
    -jre-restrict-search | -jre-no-restrict-search
                  include/exclude user private JREs in the version search
    -? -help      print this help message
    -X            print help on non-standard options
    -ea[:…|:]
    -enableassertions[:…|:]
                  enable assertions
    -da[:…|:]
    -disableassertions[:…|:]
                  disable assertions
    -esa | -enablesystemassertions
                  enable system assertions
    -dsa | -disablesystemassertions
                  disable system assertions
    -agentlib:<libname>[=]
                  load native agent library <libname>, e.g. -agentlib:hprof
                    see also, -agentlib:jdwp=help and -agentlib:hprof=help
    -agentpath:<pathname>[=]
                  load native agent library by full pathname
    -javaagent:<jarpath>[=]
                  load Java programming language agent, see java.lang.instrument
———————————————————————–
在控制台输出信息中,有个-X(注意是大写)的命令,这个正是查看JVM配置参数的命令。
 
其次,用java -X 命令查看JVM的配置说明:
运行后如下结果,这些就是配置JVM参数的秘密武器,这些信息都是英文的,为了方便阅读,我根据自己的理解翻译成中文了(不准确的地方还请各位博友斧正)
———————————————————————–
D:j2sdk15bin>java -X
    -Xmixed           mixed mode execution (default)
    -Xint             interpreted mode execution only
    -Xbootclasspath:<directories and zip/jar files separated by ;>
                      set search path for bootstrap classes and resources
    -Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
    -Xbootclasspath/p:<directories and zip/jar files separated by ;>
                      prepend in front of bootstrap class path
    -Xnoclassgc       disable class garbage collection
    -Xincgc           enable incremental garbage collection
    -Xloggc:<file>    log GC status to a file with time stamps
    -Xbatch           disable background compilation
    -Xms<size>        set initial Java heap size
    -Xmx<size>        set maximum Java heap size
    -Xss<size>        set java thread stack size
    -Xprof            output cpu profiling data
    -Xfuture          enable strictest checks, anticipating future default
    -Xrs              reduce use of OS signals by Java/VM (see documentation)
    -Xcheck:jni       perform additional checks for JNI functions
    -Xshare:off       do not attempt to use shared class data
    -Xshare:auto      use shared class data if possible (default)
    -Xshare:on        require using shared class data, otherwise fail.
 
The -X options are non-standard and subject to change without notice.
———————————————————————–
 
JVM配置参数中文说明:
———————————————————————–
1、-Xmixed           mixed mode execution (default)
 混合模式执行
 
2、-Xint             interpreted mode execution only
 解释模式执行
 
3、-Xbootclasspath:<directories and zip/jar files separated by ;>
      set search path for bootstrap classes and resources
 设置zip/jar资源或者类(.class文件)存放目录路径
 
3、-Xbootclasspath/a:<directories and zip/jar files separated by ;>
      append to end of bootstrap class path
 追加zip/jar资源或者类(.class文件)存放目录路径
 
4、-Xbootclasspath/p:<directories and zip/jar files separated by ;>
      prepend in front of bootstrap class path
 预先加载zip/jar资源或者类(.class文件)存放目录路径
 
5、-Xnoclassgc       disable class garbage collection
 关闭类垃圾回收功能
 
6、-Xincgc           enable incremental garbage collection
 开启类的垃圾回收功能
 
7、-Xloggc:<file>    log GC status to a file with time stamps
 记录垃圾回日志到一个文件。
 
8、-Xbatch           disable background compilation
 关闭后台编译
 
9、-Xms<size>        set initial Java heap size
 设置JVM初始化堆内存大小
 
10、-Xmx<size>        set maximum Java heap size
 设置JVM最大的堆内存大小
 
11、-Xss<size>        set java thread stack size
 设置JVM栈内存大小
 
12、-Xprof            output cpu profiling data
 输入CPU概要表数据
 
13、-Xfuture          enable strictest checks, anticipating future default
 执行严格的代码检查,预测可能出现的情况
 
14、-Xrs              reduce use of OS signals by Java/VM (see documentation)
 通过JVM还原操作系统信号
 
15、-Xcheck:jni       perform additional checks for JNI functions
 对JNI函数执行检查
 
16、-Xshare:off       do not attempt to use shared class data
 尽可能不去使用共享类的数据
 
17、-Xshare:auto      use shared class data if possible (default)
 尽可能的使用共享类的数据
 
18、-Xshare:on       require using shared class data, otherwise fail.
 尽可能的使用共享类的数据,否则运行失败
 
The -X options are non-standard and subject to change without notice.
———————————————————————–
 
怎么用这这些参数呢?其实所有的命令行都是这么一用,下面我就给出一个最简单的HelloWorl的例子来演示这个参数的用法,非常的简单。
 
HelloWorld.java
———————————————–
public class  HelloWorld
{
 public static void main(String[] args)
 {
  System.out.println(“Hello World!”);
 }
}
 
编译并运行:
D:j2sdk15bin>javac HelloWorld.java
 
D:j2sdk15bin>java -Xms256M -Xmx512M HelloWorld
Hello World!
 
呵呵,这下满足了吧!
 
实践:在大型系统或者应用中配置JVM参数
比如你配置IDE工具的参数,常见的有IDEA、Eclipse,这个是在一个配置文件中指定即可。
如果你要在J2EE环境中配置这些参数,那么你需要在J2EE应用服务器或者Servlet容器相关启动参数设置处指定,其启动文件中来配置,Tomcat是在catalina.bat中配置,weblogic和websphere是在其他地方,具体我就说了,相信玩过的这些大型服务器的人都知道,没玩过的看看这篇文章,玩玩就知道了,呵呵。
 
另外常常有人问到jdk的一些相关命令用法,其实,当你看到这里的时候,你应该知道如何获取这些命令的用法了。如果你还不会,那么,建议你去学学DOS,我是没辙了。如果你会这些,还是没有看明白,那么你赶紧学学英语吧,这样你就能看懂了。
 
另外:我在最后给出常用的几个Java命令行说明,以供参考:
 
(1)、javac
用法:javac <选项> <源文件>
其中,可能的选项包括:
  -g                         生成所有调试信息
  -g:none                    不生成任何调试信息
  -g:{lines,vars,source}     只生成某些调试信息
  -nowarn                    不生成任何警告
  -verbose                   输出有关编译器正在执行的操作的消息
  -deprecation               输出使用已过时的 API 的源位置
  -classpath <路径>            指定查找用户类文件的位置
  -cp <路径>                   指定查找用户类文件的位置
  -sourcepath <路径>           指定查找输入源文件的位置
  -bootclasspath <路径>        覆盖引导类文件的位置
  -extdirs <目录>              覆盖安装的扩展目录的位置
  -endorseddirs <目录>         覆盖签名的标准路径的位置
  -d <目录>                    指定存放生成的类文件的位置
  -encoding <编码>             指定源文件使用的字符编码
  -source <版本>               提供与指定版本的源兼容性
  -target <版本>               生成特定 VM 版本的类文件
  -version                   版本信息
  -help                      输出标准选项的提要
  -X                         输出非标准选项的提要
  -J<标志>                     直接将 <标志> 传递给运行时系统
 
(2)、jar
用法:jar {ctxu}[vfm0Mi] [jar-文件] [manifest-文件] [-C 目录] 文件名 …
选项:
    -c  创建新的存档
    -t  列出存档内容的列表
    -x  展开存档中的命名的(或所有的〕文件
    -u  更新已存在的存档
    -v  生成详细输出到标准输出上
    -f  指定存档文件名
    -m  包含来自标明文件的标明信息
    -0  只存储方式;未用ZIP压缩格式
    -M  不产生所有项的清单(manifest〕文件
    -i  为指定的jar文件产生索引信息
    -C  改变到指定的目录,并且包含下列文件:
如果一个文件名是一个目录,它将被递归处理。
清单(manifest〕文件名和存档文件名都需要被指定,按’m’ 和 ‘f’标志指定的相同顺序。
 
示例1:将两个class文件存档到一个名为 ‘classes.jar’ 的存档文件中:
       jar cvf classes.jar Foo.class Bar.class
示例2:用一个存在的清单(manifest)文件 ‘mymanifest’ 将 foo/ 目录下的所有
           文件存档到一个名为 ‘classes.jar’ 的存档文件中:
       jar cvfm classes.jar mymanifest -C foo/ .
 
(3)、javadoc
javadoc: 错误 – 未指定软件包或类。
用法:javadoc [选项] [软件包名称] [源文件] [@file]
-overview <文件>          读取 HTML 文件的概述文档
-public                   仅显示公共类和成员
-protected                显示受保护/公共类和成员(默认)
-package                  显示软件包/受保护/公共类和成员
-private                  显示所有类和成员
-help                     显示命令行选项并退出
-doclet <类>              通过替代 doclet 生成输出
-docletpath <路径>        指定查找 doclet 类文件的位置
-sourcepath <路径列表>    指定查找源文件的位置
-classpath <路径列表>     指定查找用户类文件的位置
-exclude <软件包列表>     指定要排除的软件包的列表
-subpackages <子软件包列表> 指定要递归装入的子软件包
-breakiterator            使用 BreakIterator 计算第 1 句
-bootclasspath <路径列表> 覆盖引导类加载器所装入的
                          类文件的位置
-source <版本>            提供与指定版本的源兼容性
-extdirs <目录列表>       覆盖安装的扩展目录的位置
-verbose                  输出有关 Javadoc 正在执行的操作的消息
-locale <名称>            要使用的语言环境,例如 en_US 或 en_US_WIN
-encoding <名称>          源文件编码名称
-quiet                    不显示状态消息
-J<标志>                  直接将 <标志> 传递给运行时系统
 
通过标准 doclet 提供:
-d <目录>                         输出文件的目标目录
-use                              创建类和软件包用法页面
-version                          包含 @version 段
-author                           包含 @author 段
-docfilessubdirs                  递归复制文档文件子目录
-splitindex                       将索引分为每个字母对应一个文件
-windowtitle <文本>               文档的浏览器窗口标题
-doctitle <html 代码>             包含概述页面的标题
-header <html 代码>               包含每个页面的页眉文本
-footer <html 代码>               包含每个页面的页脚文本
-bottom <html 代码>               包含每个页面的底部文本
-link <url>                       创建指向位于 <url> 的 javadoc 输出的链接
-linkoffline <url> <url2>         利用位于 <url2> 的软件包列表链接至位于 <url>
的文档
-excludedocfilessubdir <名称 1>:..排除带有给定名称的所有文档文件子目录。
-group <名称> <p1>:<p2>..         在概述页面中,将指定的软件包分组
-nocomment                        抑止描述和标记,只生成声明。
-nodeprecated                     不包含 @deprecated 信息
-noqualifier <名称 1>:<名称 2>:…从输出中排除限定符的列表。
-nosince                          不包含 @since 信息
-notimestamp                      不包含隐藏时间戳
-nodeprecatedlist                 不生成已过时的列表
-notree                           不生成类分层结构
-noindex                          不生成索引
-nohelp                           不生成帮助链接
-nonavbar                         不生成导航栏
-serialwarn                       生成有关 @serial 标记的警告
-tag <名称>:<位置>:<标题>         指定单个变量自定义标记
-taglet                           要注册的 Taglet 的全限定名称
-tagletpath                       Taglet 的路径
-charset <字符集>                 用于跨平台查看生成的文档的字符集。
-helpfile <文件>                  包含帮助链接所链接到的文件
-linksource                       以 HTML 格式生成源
-sourcetab <制表符长度>           指定源中每个制表符占据的空格数
-keywords                         使软件包、类和成员信息附带 HTML 元标记
-stylesheetfile <路径>            用于更改生成文档的样式的文件
-docencoding <名称>               输出编码名称
 
(4)、rmid
rmid: 非法选项:-?
用法:rmid <option>
 
其中,<option> 包括:
  -port <option>        指定供 rmid 使用的端口
  -log <directory>    指定 rmid 将日志写入的目录
  -stop               停止当前的 rmid 调用(对指定端口)
  -C<runtime 标记>    向每个子进程传递参数(激活组)
  -J<runtime 标记>    向 java 解释程序传递参数

有关更多的java命令可以参考一下这个文章:

http://ruruhuang.javaeye.com/blog/47564

 

http://kenwublog.com/docs/java6-jvm-options-chinese-edition.htm

以上资料转自:http://lavasoft.blog.51cto.com/62575/25492

一些有用的-XX选项,来自oracle:

Behavioral Options

Option and Default Value Description
-XX:-AllowUserSignalHandlers Do not complain if the application installs signal handlers. (Relevant to Solaris and Linux only.)
-XX:AltStackSize=16384 Alternate signal stack size (in Kbytes). (Relevant to Solaris only, removed from 5.0.)
-XX:-DisableExplicitGC By default calls to System.gc() are enabled (-XX:-DisableExplicitGC). Use -XX:+DisableExplicitGC to disable calls to System.gc(). Note that the JVM still performs garbage collection when necessary.
-XX:+FailOverToOldVerifier Fail over to old verifier when the new type checker fails. (Introduced in 6.)
-XX:+HandlePromotionFailure The youngest generation collection does not require a guarantee of full promotion of all live objects. (Introduced in 1.4.2 update 11) [5.0 and earlier: false.]
-XX:+MaxFDLimit Bump the number of file descriptors to max. (Relevant  to Solaris only.)
-XX:PreBlockSpin=10 Spin count variable for use with -XX:+UseSpinning. Controls the maximum spin iterations allowed before entering operating system thread synchronization code. (Introduced in 1.4.2.)
-XX:-RelaxAccessControlCheck Relax the access control checks in the verifier. (Introduced in 6.)
-XX:+ScavengeBeforeFullGC Do young generation GC prior to a full GC. (Introduced in 1.4.1.)
-XX:+UseAltSigs Use alternate signals instead of SIGUSR1 and SIGUSR2 for VM internal signals. (Introduced in 1.3.1 update 9, 1.4.1. Relevant to Solaris only.)
-XX:+UseBoundThreads Bind user level threads to kernel threads. (Relevant to Solaris only.)
-XX:-UseConcMarkSweepGC Use concurrent mark-sweep collection for the old generation. (Introduced in 1.4.1)
-XX:+UseGCOverheadLimit Use a policy that limits the proportion of the VM’s time that is spent in GC before an OutOfMemory error is thrown. (Introduced in 6.)
-XX:+UseLWPSynchronization Use LWP-based instead of thread based synchronization. (Introduced in 1.4.0. Relevant to Solaris only.)
-XX:-UseParallelGC Use parallel garbage collection for scavenges. (Introduced in 1.4.1)
-XX:-UseParallelOldGC Use parallel garbage collection for the full collections. Enabling this option automatically sets -XX:+UseParallelGC. (Introduced in 5.0 update 6.)
-XX:-UseSerialGC Use serial garbage collection. (Introduced in 5.0.)
-XX:-UseSpinning Enable naive spinning on Java monitor before entering operating system thread synchronizaton code. (Relevant to 1.4.2 and 5.0 only.) [1.4.2, multi-processor Windows platforms: true]
-XX:+UseTLAB Use thread-local object allocation (Introduced in 1.4.0, known as UseTLE prior to that.) [1.4.2 and earlier, x86 or with -client: false]
-XX:+UseSplitVerifier Use the new type checker with StackMapTable attributes. (Introduced in 5.0.)[5.0: false]
-XX:+UseThreadPriorities Use native thread priorities.
-XX:+UseVMInterruptibleIO Thread interrupt before or with EINTR for I/O operations results in OS_INTRPT. (Introduced in 6. Relevant to Solaris only.)

Back to Options 
  


Garbage First (G1) Garbage Collection Options

Option and Default Value Description
-XX:+UseG1GC Use the Garbage First (G1) Collector
-XX:MaxGCPauseMillis=n Sets a target for the maximum GC pause time. This is a soft goal, and the JVM will make its best effort to achieve it.
-XX:InitiatingHeapOccupancyPercent=n Percentage of the (entire) heap occupancy to start a concurrent GC cycle. It is used by GCs that trigger a concurrent GC cycle based on the occupancy of the entire heap, not just one of the generations (e.g., G1). A value of 0 denotes ‘do constant GC cycles’. The default value is 45.
-XX:NewRatio=n Ratio of old/new generation sizes. The default value is 2.
-XX:SurvivorRatio=n Ratio of eden/survivor space size. The default value is 8.
-XX:MaxTenuringThreshold=n Maximum value for tenuring threshold. The default value is 15.
-XX:ParallelGCThreads=n Sets the number of threads used during parallel phases of the garbage collectors. The default value varies with the platform on which the JVM is running.
-XX:ConcGCThreads=n Number of threads concurrent garbage collectors will use. The default value varies with the platform on which the JVM is running.
-XX:G1ReservePercent=n Sets the amount of heap that is reserved as a false ceiling to reduce the possibility of promotion failure. The default value is 10.
-XX:G1HeapRegionSize=n With G1 the Java heap is subdivided into uniformly sized regions. This sets the size of the individual sub-divisions. The default value of this parameter is determined ergonomically based upon heap size. The minimum value is 1Mb and the maximum value is 32Mb.

Back to Options 
 


Performance Options

Option and Default Value Description
-XX:+AggressiveOpts Turn on point performance compiler optimizations that are expected to be default in upcoming releases. (Introduced in 5.0 update 6.)
-XX:CompileThreshold=10000 Number of method invocations/branches before compiling [-client: 1,500]
-XX:LargePageSizeInBytes=4m Sets the large page size used for the Java heap. (Introduced in 1.4.0 update 1.) [amd64: 2m.]
-XX:MaxHeapFreeRatio=70 Maximum percentage of heap free after GC to avoid shrinking.
-XX:MaxNewSize=size Maximum size of new generation (in bytes). Since 1.4, MaxNewSize is computed as a function of NewRatio. [1.3.1 Sparc: 32m; 1.3.1 x86: 2.5m.]
-XX:MaxPermSize=64m Size of the Permanent Generation.  [5.0 and newer: 64 bit VMs are scaled 30% larger; 1.4 amd64: 96m; 1.3.1 -client: 32m.]
-XX:MinHeapFreeRatio=40 Minimum percentage of heap free after GC to avoid expansion.
-XX:NewRatio=2 Ratio of old/new generation sizes. [Sparc -client: 8; x86 -server: 8; x86 -client: 12.]-client: 4 (1.3) 8 (1.3.1+), x86: 12]
-XX:NewSize=2m Default size of new generation (in bytes) [5.0 and newer: 64 bit VMs are scaled 30% larger; x86: 1m; x86, 5.0 and older: 640k]
-XX:ReservedCodeCacheSize=32m Reserved code cache size (in bytes) – maximum code cache size. [Solaris 64-bit, amd64, and -server x86: 2048m; in 1.5.0_06 and earlier, Solaris 64-bit and amd64: 1024m.]
-XX:SurvivorRatio=8 Ratio of eden/survivor space size [Solaris amd64: 6; Sparc in 1.3.1: 25; other Solaris platforms in 5.0 and earlier: 32]
-XX:TargetSurvivorRatio=50 Desired percentage of survivor space used after scavenge.
-XX:ThreadStackSize=512 Thread Stack Size (in Kbytes). (0 means use default stack size) [Sparc: 512; Solaris x86: 320 (was 256 prior in 5.0 and earlier); Sparc 64 bit: 1024; Linux amd64: 1024 (was 0 in 5.0 and earlier); all others 0.]
-XX:+UseBiasedLocking Enable biased locking. For more details, see thistuning example. (Introduced in 5.0 update 6.) [5.0: false]
-XX:+UseFastAccessorMethods Use optimized versions of Get<Primitive>Field.
-XX:-UseISM Use Intimate Shared Memory. [Not accepted for non-Solaris platforms.] For details, see Intimate Shared Memory.
-XX:+UseLargePages Use large page memory. (Introduced in 5.0 update 5.) For details, see Java Support for Large Memory Pages.
-XX:+UseMPSS Use Multiple Page Size Support w/4mb pages for the heap. Do not use with ISM as this replaces the need for ISM. (Introduced in 1.4.0 update 1, Relevant to Solaris 9 and newer.) [1.4.1 and earlier: false]
-XX:+UseStringCache Enables caching of commonly allocated strings.
 
-XX:AllocatePrefetchLines=1 Number of cache lines to load after the last object allocation using prefetch instructions generated in JIT compiled code. Default values are 1 if the last allocated object was an instance and 3 if it was an array. 
 
-XX:AllocatePrefetchStyle=1 Generated code style for prefetch instructions.
0 – no prefetch instructions are generate*d*,
1 – execute prefetch instructions after each allocation,
2 – use TLAB allocation watermark pointer to gate when prefetch instructions are executed.
 
-XX:+UseCompressedStrings Use a byte[] for Strings which can be represented as pure ASCII. (Introduced in Java 6 Update 21 Performance Release) 
 
-XX:+OptimizeStringConcat Optimize String concatenation operations where possible. (Introduced in Java 6 Update 20) 
 

Back to Options 
  


Debugging Options

Option and Default Value Description
-XX:-CITime Prints time spent in JIT Compiler. (Introduced in 1.4.0.)
-XX:ErrorFile=./hs_err_pid<pid>.log If an error occurs, save the error data to this file. (Introduced in 6.)
-XX:-ExtendedDTraceProbes Enable performance-impacting dtrace probes. (Introduced in 6. Relevant to Solaris only.)
-XX:HeapDumpPath=./java_pid<pid>.hprof Path to directory or filename for heap dump.Manageable. (Introduced in 1.4.2 update 12, 5.0 update 7.)
-XX:-HeapDumpOnOutOfMemoryError Dump heap to file when java.lang.OutOfMemoryError is thrown. Manageable. (Introduced in 1.4.2 update 12, 5.0 update 7.)
-XX:OnError=”<cmd args>;<cmd args>” Run user-defined commands on fatal error. (Introduced in 1.4.2 update 9.)
-XX:OnOutOfMemoryError=”<cmd args>; 
<cmd args>”
Run user-defined commands when an OutOfMemoryError is first thrown. (Introduced in 1.4.2 update 12, 6)
-XX:-PrintClassHistogram Print a histogram of class instances on Ctrl-Break.Manageable. (Introduced in 1.4.2.) The jmap -histocommand provides equivalent functionality.
-XX:-PrintConcurrentLocks Print java.util.concurrent locks in Ctrl-Break thread dump. Manageable. (Introduced in 6.) The jstack -lcommand provides equivalent functionality.
-XX:-PrintCommandLineFlags Print flags that appeared on the command line. (Introduced in 5.0.)
-XX:-PrintCompilation Print message when a method is compiled.
-XX:-PrintGC Print messages at garbage collection. Manageable.
-XX:-PrintGCDetails Print more details at garbage collection. Manageable. (Introduced in 1.4.0.)
-XX:-PrintGCTimeStamps Print timestamps at garbage collection. Manageable(Introduced in 1.4.0.)
-XX:-PrintTenuringDistribution Print tenuring age information.
-XX:-PrintAdaptiveSizePolicy Enables printing of information about adaptive generation sizing.
-XX:-TraceClassLoading Trace loading of classes.
-XX:-TraceClassLoadingPreorder Trace all classes loaded in order referenced (not loaded). (Introduced in 1.4.2.)
-XX:-TraceClassResolution Trace constant pool resolutions. (Introduced in 1.4.2.)
-XX:-TraceClassUnloading Trace unloading of classes.
-XX:-TraceLoaderConstraints Trace recording of loader constraints. (Introduced in 6.)
-XX:+PerfDataSaveToFile Saves jvmstat binary data on exit.
-XX:ParallelGCThreads=n Sets the number of garbage collection threads in the young and old parallel garbage collectors. The default value varies with the platform on which the JVM is running.
-XX:+UseCompressedOops Enables the use of compressed pointers (object references represented as 32 bit offsets instead of 64-bit pointers) for optimized 64-bit performance with Java heap sizes less than 32gb.
-XX:+AlwaysPreTouch Pre-touch the Java heap during JVM initialization. Every page of the heap is thus demand-zeroed during initialization rather than incrementally during application execution.
-XX:AllocatePrefetchDistance=n Sets the prefetch distance for object allocation. Memory about to be written with the value of new objects is prefetched into cache at this distance (in bytes) beyond the address of the last allocated object. Each Java thread has its own allocation point. The default value varies with the platform on which the JVM is running.
-XX:InlineSmallCode=n Inline a previously compiled method only if its generated native code size is less than this. The default value varies with the platform on which the JVM is running.
-XX:MaxInlineSize=35 Maximum bytecode size of a method to be inlined.
-XX:FreqInlineSize=n Maximum bytecode size of a frequently executed method to be inlined. The default value varies with the platform on which the JVM is running.
-XX:LoopUnrollLimit=n Unroll loop bodies with server compiler intermediate representation node count less than this value. The limit used by the server compiler is a function of this value, not the actual value. The default value varies with the platform on which the JVM is running.
-XX:InitialTenuringThreshold=7 Sets the initial tenuring threshold for use in adaptive GC sizing in the parallel young collector. The tenuring threshold is the number of times an object survives a young collection before being promoted to the old, or tenured, generation.
-XX:MaxTenuringThreshold=n Sets the maximum tenuring threshold for use in adaptive GC sizing. The current largest value is 15. The default value is 15 for the parallel collector and is 4 for CMS.
-Xloggc:<filename> Log GC verbose output to specified file. The verbose output is controlled by the normal verbose GC flags.
-XX:-UseGCLogFileRotation Enabled GC log rotation, requires -Xloggc.
-XX:NumberOfGClogFiles=1 Set the number of files to use when rotating logs, must be >= 1. The rotated log files will use the following naming scheme, <filename>.0, <filename>.1, …, <filename>.n-1.
-XX:GCLogFileSize=8K The size of the log file at which point the log will be rotated, must be >= 8K.

以上参数来自官网:http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html