安装zeromq

2010年5月6日 由 飞扬轻狂 2 条评论 »

- 安装zeromq

$ wget http://www.zeromq.org/local--files/area:download/zeromq-2.0.6.tar.gz
$ tar -xzf zeromq-2.0.6.tar.gz
$ cd zeromq-2.0.6
$ ./configure --prefix=/home/app/zeromq
$ make
$ sudo make install
// 重建so文件链接
$ sudo ln -s /home/app/zeromq/lib/libzmq.so.0.0.0 /usr/lib/libzmq.so.0
$ sudo ln -s /home/app/zeromq/lib/libzmq.so.0.0.0 /usr/lib/libzmq.so

- 测试zeromq

// client.c
#include
#include
#include
#include "/home/app/zeromq/include/zmq.h"

int main ()
{
int rc;
void *ctx, *s;
zmq_msg_t query, resultset;
const char *query_string, *resultset_string = "OK";

/* Initialise 0MQ context, requesting a single application thread
and a single I/O thread */
ctx = zmq_init (1, 1, 0);
assert (ctx);
/* Create a ZMQ_REP socket to receive requests and send replies */
s = zmq_socket (ctx, ZMQ_REP);
assert (s);
/* Bind to the TCP transport and port 5555 on the 'lo' interface */
rc = zmq_bind (s, "tcp://lo:5555");
assert (rc == 0);

while (1) {
/* Allocate an empty message to receive a query into */
rc = zmq_msg_init (&query);
assert (rc == 0);

/* Receive a message, blocks until one is available */
rc = zmq_recv (s, &query, 0);
assert (rc == 0);

/* Process the query */
query_string = (const char *)zmq_msg_data (&query);
printf ("Received query: '%s'\n", query_string);
zmq_msg_close (&query);

/* Allocate a response message and fill in an example response */
rc = zmq_msg_init_size (&resultset, strlen (resultset_string) + 1);
assert (rc == 0);
memcpy (zmq_msg_data (&resultset),
resultset_string, strlen (resultset_string) + 1);

/* Send back our canned response */
rc = zmq_send (s, &resultset, 0);
assert (rc == 0);
zmq_msg_close (&resultset);
}
}


// server.cpp
#include
#include "/home/app/zeromq/include/zmq.hpp"

int main ()
{
try {
// Initialise 0MQ context with one application and one I/O thread
zmq::context_t ctx (1, 1);
// Create a ZMQ_REQ socket to send requests and receive replies
zmq::socket_t s (ctx, ZMQ_REQ);
// Connect it to port 5555 on localhost using the TCP transport
s.connect ("tcp://localhost:5555");

// Construct an example zmq::message_t with our query
const char *query_string = "SELECT * FROM mytable";
zmq::message_t query (strlen (query_string) + 1);
memcpy (query.data (), query_string, strlen (query_string) + 1);
// Send the query
s.send (query);

// Receive and display the result
zmq::message_t resultset;
s.recv (&resultset);
const char *resultset_string = (const char *)resultset.data ();
printf ("Received response: '%s'\n", resultset_string);
}
catch (std::exception &e) {
// 0MQ throws standard exceptions just like any other C++ API
printf ("An error occurred: %s\n", e.what());
return 1;
}

return 0;
}


// 编译
$ gcc `pkg-config --libs --cflags /home/app/zeromq/lib/pkgconfig/libzmq.pc` -o server server.c
$ g++ `pkg-config --libs --cflags /home/app/zeromq/lib/pkgconfig/libzmq.pc` -o client client.cpp

注意:将so链接到usr/lib下 测试程序才运行成功!

- 安装java扩展不成功

configure.in:3: error: Autoconf version 2.61 or higher is required

$ autoreconf --version
autoreconf (GNU Autoconf) 2.59

没有时间细弄了 下次有时间再试吧 准备看下 activemq去

PHP AES-CBC 密钥插件使用实例

2010年5月5日 由 飞扬轻狂 没有评论 »


// 安装 MCrypt 包
$ wget http://downloads.sourceforge.net/project/mcrypt/Libmcrypt/2.5.8/libmcrypt-2.5.8.tar.gz?use_mirror=cdnetworks-kr-2
$ tar -xzf libmcrypt-2.5.8.tar.gz
$ cd libmcrypt-2.5.8
$ ./configure --prefix=/home/app/libmcrypt-2.5.8
$ make
$ sudo make install
// 编译 php
$ wget http://cn.php.net/get/php-5.2.13.tar.gz/from/this/mirror
$ tar -xzf php-5.2.13.tar.gz
$ cd php-5.2.13/ext/mcrypt/
$ /home/php-5.2.0/bin/phpize
$ ./configure --with-php-config=/home/php-5.2.0/bin/php-config --with-mcrypt=/home/app/libmcrypt-2.5.8/
$ sudo mkdir -p /home/php5/lib/php/extensions/no-debug-non-zts-20060613
$ sudo cp -p modules/mcrypt.so /home/php5/lib/php/extensions/no-debug-non-zts-20060613/

测试:

dl("mcrypt.so");
$string = "test@abc.com";
$stuff="String to enc/enc/dec/dec =,=,";
$key="XiTo74dOO09N48YeUmuvbL0E";
$iv = mcrypt_create_iv (mcrypt_get_block_size (MCRYPT_TripleDES, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM);

$iv64=base64_encode($iv);
echo "iv:".base64_encode($iv);
echo "
\n";

$key=base64_decode("U42/zc3r6zC2Ok11BqO+lA==");
$iv=base64_decode("xTXaC2FQEGWOVBqPIipt1A==");
//$enc=mcrypt_cbc (MCRYPT_TripleDES, $key, $string, MCRYPT_ENCRYPT, $iv);
//MCRYPT_RIJNDAEL_128
$enc=mcrypt_cbc (MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_ENCRYPT, $iv);
$ret=base64_encode($enc);

echo "encrypt:".$ret;
echo "
\n";
$string=$ret;
$string = trim(base64_decode($string));
//$dec = mcrypt_cbc (MCRYPT_TripleDES, $key, $string, MCRYPT_DECRYPT, $iv);
$dec = mcrypt_cbc (MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_DECRYPT, $iv);

echo "decrypt:".$dec;

1、声明不定长的方法 – 需要知道的9个PHP实用方法

2010年5月5日 由 飞扬轻狂 1条评论 »

偶尔翻看 美味书签 发现这篇了这篇文章 就迫不急待的把她保留在自己的空间了
虽然这篇文章中提到的方法只有个别的几个不知道,但这些东西确实很少被使用和初学者知道
摘自: 9 Useful PHP Functions and Features You Need to Know

————— 英文不好,咱只过代码 ~ O(∩_∩)O ~ ———————-
1. 声明不定长参数个数的方法
这个功能在函数库里经常会用到如printf中参数的个数就是不固定的
样例

// 声明空参数的方法, PHP是动态语言,所以在调用时可以不遵守约定输入任意参数~~
// 如果在java里 需要这样声明 foo(Object ... args)
function foo() {
// 得到所有的传递进来的实际参数值(实参)
$args = func_get_args();
// 将所得到的实参输出
foreach ($args as $k => $v) {
echo "arg".($k+1).": $v\n";
}
}

foo();
/* 什么都不打印 */

foo('hello');
/* 打印
arg1: hello
*/

foo('hello', 'world', 'again');
/* 打印
arg1: hello
arg2: world
arg3: again
*/

这个功能很实用,书写起来也很直观
类似的PHP为我们提供的方法处理函数还有:
– 获取当前方法本次调用时的参数信息
func_get_arg 获取当次方法调用的指定位置的参数
func_get_args 获取当次方法调用的参数列表
func_num_args 获取当次方法调用的参数个数
– 扩展: 通过字面量调用已定义的方法 , 允许通过变量传递方法名,将调用方和实现方解耦
function_exists 验证方法是否存在
call_user_func 通过方法名调用方法
method_exists 验证成员方法是否存在
forward_static_call 在成员方法中调用外部静态方法

HelloWorld Java 2: Arguments & Signal

2010年3月26日 由 飞扬轻狂 没有评论 »

使用apache的commons.cli解析命令行参数
Java Code:

package test.helloworld.cmd;
// fallseir 2010-03-26
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class Cli {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		GnuParser parser=new GnuParser();
		Options opts=getCmdOptions();
		CommandLine line=null;
		try {
			line=parser.parse(opts,args);
		} catch (ParseException e) {
			//e.printStackTrace();
			System.err.println(e.getMessage());
			HelpFormatter helper=new HelpFormatter();
			helper.printHelp("cmdLineSyntax", opts);
		}
		if(line==null) return ;
		if(line.hasOption("h")){
			HelpFormatter helper=new HelpFormatter();
			//helper.printHelp("cmdLineSyntax", opts);
			helper.printHelp(80, "tester", "header", opts, "footer");
			return;
		}
		boolean debug=false;
		if(line.hasOption("debug")){
			debug=true;
			System.out.println("debug is set");
		}
		if(line.hasOption("arg")){
			String arg=line.getOptionValue("arg");
			System.out.println("arg "+arg);
		}
	}

	private static Options getCmdOptions() {
		Options options=new Options();
		Option opt=OptionBuilder.create("debug");
		options.addOption(opt);
		opt=OptionBuilder.isRequired()
					.hasArg()
					.withArgName("arg")
					.withDescription("arg description")
					.withLongOpt("argument")
					.withValueSeparator()
					.create("arg");
		options.addOption(opt);
		options.addOption(new Option("h","help",false,"print help"));
		return options;
	}

}

Signal Shell下基于信号的应用通信
使用 sun.misc.Signal ,但 sun 已经提示Signal将在其后版本剥离
建议使用 socket 进行通信吧

package test.helloworld.cmd;
// fallseir 2010-03-26
import sun.misc.Signal;
import sun.misc.SignalHandler;

public class SignalHandle {
	public static void main(String args[]){
		System.out.println("start");
		SignalHandle cmd=new SignalHandle();
		if(cmd.isLinux()){
			cmd.installSignalHandler("QUIT");
			cmd.installSignalHandler("HUP");
			cmd.installSignalHandler("USR1");
			cmd.installSignalHandler("USR2");
			cmd.installSignalHandler("PIPE");
		}
		cmd.installSignalHandler("TERM");
		cmd.installSignalHandler("ABRT");
		cmd.installSignalHandler("INT");
		try{
			Thread.sleep(1000*10*10);
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}
	private void handleSignal(String signal){
		System.out.println("handleSignal "+signal);
	}
	private boolean isLinux() {
		return System.getProperty("os.name").indexOf("Linux")>=0;
	}
	private void installSignalHandler(String signal){
		System.out.println("installCheckSignal "+signal);
		SimpleSignalHandler shandler=new SimpleSignalHandler();
		try{
			SignalHandler old = Signal.handle( new Signal( signal ), shandler);
			shandler.setOld(old);
		}catch(Exception e){
			System.err.println("installShutdownSignal "+signal+" "+e);
		}
	}
	class SimpleSignalHandler implements SignalHandler{
		SignalHandler old=null;
		public SimpleSignalHandler() {
		}
		public void handle( Signal sig ) {
			try{
				System.out.println("Handle Signal "+sig.getName() );
				handSignal(sig);
				if( old != null && old != SIG_DFL && old != SIG_IGN ) {  //chain back to previous handler if one exists
					old.handle( sig );
				}
			}
			catch( Throwable t ) {
				System.out.println(String.format("ShutdownSignalHandler.handle %s : %s",sig.getName(),t.getMessage())+t);
			}
		}
		protected void handSignal(Signal sig) {
			handleSignal(sig.getName());
		}
		public void setOld(SignalHandler old){
			this.old=old;
		}
	}
}

HelloWorld Java 1: ShutdownHook & start/stop Script

2010年3月26日 由 飞扬轻狂 没有评论 »

Java 代码:

package test.helloworld.cmd;
// by fallseir 2010-03-26
public class ShutdownHook {
	public static void main(String args[]){
		System.out.println("start");
		ShutdownHook cmd=new ShutdownHook();
		cmd.installShutdownHook();
		try{
			Thread.sleep(1000*10*10);
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}
	private void shutdown(){
		System.out.println("shutdown");
	}
	private void installShutdownHook(){
		Runtime.getRuntime().addShutdownHook(new Thread(){
			public void run(){
				shutdown();
			}
		});
	}
}

sh 代码:

#!/bin/sh
# -----------------------------------------------------------------------------
# fallseir 2010-03-26
# Start/Stop Script for the test.helloworld.cmd.ShutdownHook system
# run.sh start|stop|check
#
base="."
lib="$base/lib"
log="$base/log"

app="run"
mainCls="test.helloworld.cmd.ShutdownHook"
pid="$app"".pid"

cp=""
#cp="$cp:$lib/log4j-1.2.13.jar"

cmd="java -cp $cp $mainCls $args"

ARG=$1
if [ "x$ARG" = "x" ] ; then
  ARG="start"
else
  shift
fi

if [ ! -d "$log" ] ; then
  mkdir "$log"
fi

if [ "$ARG" = "start" ] ; then
  AppErr="$log/$app.err"
  AppOut="$log/$app.out"
  # 备份历史日志
  if [ -f "$AppErr" ] ; then
    mv "$AppErr" "$AppErr".`date +%Y%m%d`"."$$
  fi
  if [ -f "$AppOut" ] ; then
    mv "$AppOut" "$AppOut".`date +%Y%m%d`"."$$
  fi
  # 在后台启动应用
  echo "$cmd $@ > $AppOut 2> $AppErr"
  $cmd "$@" > "$AppOut" 2> "$AppOut" &
  # 记录进程ID
  if [ ! -z "$pid" ] ; then
    echo $! > $pid
  fi
# 使用USR2 进行简单通信
#elif [ "$ARG" = "check" ] ; then
#  if [ ! -z "$pid" ]; then
#    echo "check: `cat $pid`"
#    kill -USR2 `cat $pid`
#  else
#    echo "Kill failed: \$pid not set"
#  fi
elif [ "$ARG" = "stop" ] ; then
  # kill 应用进程
  if [ ! -z "$pid" ]; then
    echo "Killing: `cat $pid`"
    kill -15 `cat $pid`
    rm $pid
  else
    echo "Kill failed: \$pid not set"
  fi
fi