首页 文章 精选 留言 我的

精选列表

搜索[TDSQL-C PostgreSQL 版],共10000篇文章
优秀的个人博客,低调大师

LAMP架构升级版--LNMMP

简介 LNMMP=Linux+Nginx+MySQL+Memcache+PHP; 利用Nginx的高性能特点做前端反向代理服务器,分发用户请求,并在能够利用缓存的地方使用Memcache缓存服务,以加速缓存效率,具体架构图如下; 具体部署 代理层:Nginx 编译安装Nginx 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 yum install gcc openssl-devel pcre-devel zlib-devel groupadd -r nginx useradd -r -g nginx -M nginx . /configure \ --prefix= /usr/local/nginx \ --sbin-path= /usr/sbin/nginx \ --conf-path= /etc/nginx/nginx .conf \ --error-log-path= /var/log/nginx/error .log \ --http-log-path= /var/log/nginx/access .log \ --pid-path= /var/run/nginx/nginx .pid \ --lock-path= /var/lock/nginx .lock \ --user=nginx \ --group=nginx \ --with-http_ssl_module \ --with-http_flv_module \ --with-http_stub_status_module \ --with-http_gzip_static_module \ --http-client-body-temp-path= /var/tmp/nginx/client/ \ --http-proxy-temp-path= /var/tmp/nginx/proxy/ \ --http-fastcgi-temp-path= /var/tmp/nginx/fcgi/ \ --http-uwsgi-temp-path= /var/tmp/nginx/uwsgi \ --http-scgi-temp-path= /var/tmp/nginx/scgi \ --with-pcre make && make install vi /etc/init .d /nginx # 编辑服务脚本 #!/bin/sh # # nginx - this script starts and stops the nginx daemon # # chkconfig: - 85 15 # description: Nginx is an HTTP(S) server, HTTP(S) reverse \ # proxy and IMAP/POP3 proxy server # processname: nginx # config: /etc/nginx/nginx.conf # config: /etc/sysconfig/nginx # pidfile: /var/run/nginx.pid # Source function library. . /etc/rc .d /init .d /functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. [ "$NETWORKING" = "no" ] && exit 0 nginx= "/usr/sbin/nginx" prog=$( basename $nginx) NGINX_CONF_FILE= "/etc/nginx/nginx.conf" [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx lockfile= /var/lock/subsys/nginx make_dirs() { # make required directories user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -` options=`$nginx -V 2>&1 | grep 'configure arguments:' ` for opt in $options; do if [ ` echo $opt | grep '.*-temp-path' ` ]; then value=` echo $opt | cut -d "=" -f 2` if [ ! -d "$value" ]; then # echo "creating" $value mkdir -p $value && chown -R $user $value fi fi done } start() { [ -x $nginx ] || exit 5 [ -f $NGINX_CONF_FILE ] || exit 6 make_dirs echo -n $ "Starting $prog: " daemon $nginx -c $NGINX_CONF_FILE retval=$? echo [ $retval - eq 0 ] && touch $lockfile return $retval } stop() { echo -n $ "Stopping $prog: " killproc $prog -QUIT retval=$? echo [ $retval - eq 0 ] && rm -f $lockfile return $retval } restart() { configtest || return $? stop sleep 1 start } reload() { configtest || return $? echo -n $ "Reloading $prog: " killproc $nginx -HUP RETVAL=$? echo } force_reload() { restart } configtest() { $nginx -t -c $NGINX_CONF_FILE } rh_status() { status $prog } rh_status_q() { rh_status > /dev/null 2>&1 } case "$1" in start) rh_status_q && exit 0 $1 ;; stop) rh_status_q || exit 0 $1 ;; restart|configtest) $1 ;; reload) rh_status_q || exit 7 $1 ;; force-reload) force_reload ;; status) rh_status ;; condrestart|try-restart) rh_status_q || exit 0 ;; *) echo $ "Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}" exit 2 esac 配置Nginx 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 upstream memcached { server 172.16.25.111:11211; keepalive 1024; } upstream webserver { server 172.16.25.112:80; server 172.16.25.113:80; } upstream phpserver { server 172.16.25.112:9000; server 172.16.25.113:9000; } server { listen 80; server_name xxrenzhe.lnmmp.com; access_log /var/log/nginx/lnmmp .access.log; error_log /var/log/nginx/lnmmp .errors.log notice; root /www/lnmmp .com; index index.php index.html; location / { set $memcached_key $request_uri; add_header X-mem-key $memcached_key; memcached_pass memcached; default_type test /html ; error_page 404 500 502 504 = @webnocache; } location @webnocache { rewrite ^(\/)?$ /index .php last; # 配置直接访问域名或IP地址时,重定向至index.php文件 rewrite ^/.*$ /set_mem .php?$request_uri last; # 将静态访问重定向至后端set_mem.php,以实现set memcache的功能 proxy_pass http: //webserver ; } location ~* \.php(\?.*)?$ { fastcgi_pass phpserver; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } 启动服务 1 2 3 4 chmod +x /etc/init .d /nginx chkconfig --add nginx chkconfig nginx on service nginx start 缓存层:Memcache+NFS 安装配置memcache 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 # 安装libevent tar xf libevent-2.0.21-stable. tar .gz cd libevent-2.0.21 . /configure --prefix= /usr/local/libevent make && make install echo "/usr/local/libevent/lib" > /etc/ld .so.conf.d /libevent .conf ldconfig # 安装memcache tar xf memcached-1.4.15. tar .gz cd memcached-1.4.15 . /configure --prefix= /usr/local/memcached --with-libevent= /usr/local/libevent make && make install # 编辑服务脚本 # 一次启动了2个memcache实例,一个用于Nginx,一个用于后端PHP服务 vi /etc/init .d /memcached #!/bin/bash # # Init file for memcached # # chkconfig: - 86 14 # description: Distributed memory caching daemon # # processname: memcached # config: /etc/sysconfig/memcached . /etc/rc .d /init .d /functions ## Default variables PORT1= "11211" PORT2= "11311" USER= "nobody" MAXCONN= "1024" CACHESIZE= "64" OPTIONS= "" RETVAL=0 prog= "/usr/local/memcached/bin/memcached" desc= "Distributed memory caching" lockfile1= "/var/lock/subsys/memcached_$PORT1" lockfile2= "/var/lock/subsys/memcached_$PORT2" start() { echo -n $ "Starting $desc (memcached): " daemon $prog -d -p $PORT1 -u $USER -c $MAXCONN -m $CACHESIZE -o "$OPTIONS" daemon $prog -d -p $PORT2 -u $USER -c $MAXCONN -m $CACHESIZE -o "$OPTIONS" RETVAL=$? [ $RETVAL - eq 0 ] && success && touch $lockfile1 && touch $lockfile2 || failure echo return $RETVAL } stop() { echo -n $ "Shutting down $desc (memcached): " killproc $prog RETVAL=$? [ $RETVAL - eq 0 ] && success && rm -f $lockfile1 && rm -f $lockfile2 | failure echo return $RETVAL } restart() { stop start } reload() { echo -n $ "Reloading $desc ($prog): " killproc $prog -HUP RETVAL=$? [ $RETVAL - eq 0 ] && success || failure echo return $RETVAL } case "$1" in start) start ;; stop) stop ;; restart) restart ;; condrestart) [ -e $lockfile1 ] && [ -e $lockfile1 ] && restart RETVAL=$? ;; reload) reload ;; status) status $prog RETVAL=$? ;; *) echo $ "Usage: $0 {start|stop|restart|condrestart|status}" RETVAL=1 esac exit $RETVAL 启动memcache服务 1 2 3 4 chmod +x /etc/init .d /memcached chkconfig --add memcached chkconfig memcached on service memcached start 安装配置NFS 1 2 3 4 5 6 7 8 yum -y install nfs-utils vi /etc/exports /www/lnmmp .com 172.16.0.0 /16 (rw,no_root_squash) exportfs -ar # 导出NFS共享目录 cd /www/lnmmp .com unzip phpwind_v9.0_utf8.zip mv phpwind_v9.0_utf8 /upload/ * . chmod -R 777 attachment conf data html res src themes windid Web层:Apache Apache的安装见博客“httpd-2.4编译安装及新特性详解”; PHP-fpm的安装见博客“LAMP-PHP-fpm服务器配置”; PHP加速器opcache的安装配置见博客“LAMP-各PHP加速器性能剖析”; 配置PHP支持memcache 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 tar xf memcache-2.2.5.tgz cd memcache-2.2.5 /usr/local/php/bin/phpize . /configure --with-php-config= /usr/local/php/bin/php-config -- enable -memcache make && make install # 上述安装完后会有类似这样的提示: Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/ vi /usr/local/php/lib/php .ini # 配置memcache模块位置及php会话保存至memcache中 extension= /usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/memcache .so session.save_handler = memcache session.save_path = "tcp://172.16.25.111:11311" # 自定义set memcache的程序 vi /www/lnmmp .com /set_mem .php <?php $fn = dirname (__FILE__).$_SERVER[ 'QUERY_STRING' ]; if (file_exists($fn)) { $data = file_get_contents($fn); $mem = new Memcache(); $mem->connect( "172.16.25.111" ,11311) or die( "Could not connect" ); $mem-> set ($_SERVER[ 'QUERY_STRING' ],$data,0,600) or die( "Failed to save data at the memcached server" ); header( 'Content-Length: ' .filesize($fn). "\r\n" ); header( 'Content-Type: text/html' . "\r\n" ); header( 'X-cache: MISS' . "\r\n" ); print "$data" ; } else { header( 'Location: http://xxrenzhe.lnmmp.com' . "\r\n" ); header( 'Content-Length: ' .filesize($fn). "\r\n" ); header( 'X-cache: ' .$fn. "\r\n" ); } ?> Apache配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 vi /etc/httpd/httpd .conf # DocumentRoot "/usr/local/apache/htdocs" # 注释掉此行 Include /etc/httpd/extra/httpd-vhosts .conf # 取消此行注释 vi /etc/httpd/extra/httpd-vhosts .conf <VirtualHost *:80> DocumentRoot "/www/lnmmp.com" ServerName xxrenzhe.lnmmp.com ErrorLog "logs/lnmmp.com-error_log" CustomLog "logs/lnmmp.com-access_log" common <Directory "/www/lnmmp.com" > Options Indexes FollowSymLinks AllowOverride None Require all granted < /Directory > < /VirtualHost > NFS目录挂载 1 mount -t nfs 172.16.25.111: /www/lnmmp .com /www/lnmmp .com 服务启动 1 2 service httpd start service php-fpm start 数据库层:Ameoba+MariaDB MariaDB的安装详见博客“MySQL初识-架构-安装-初始化-连接-管理工具-数据文件”; MariaDB的主从复制架构配置见博客“Maria10实现主从复制架构及SSL复制”; Ameoba安装见“http://docs.hexnova.com/amoeba/index.html”; Ameoba实现读写分离见“http://docs.hexnova.com/amoeba/rw-splitting.html” 测试验证 Nginx利用memcache缓存小静态文件测试效果 Nginx利用memcache缓存大静态文件测试效果 PHP利用memcache保存session数据测试效果 本文转自 xxrenzhe11 51CTO博客,原文链接:http://blog.51cto.com/xxrenzhe/1403784,如需转载请自行联系原作者

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

Openstack完整搭建系统整理版

Operating System How to login to Ubuntu(12.04) Server system Login as a normal user user: openstack password: password Obtain Root privilege sudo su - password: password Update Host configuration hostname controller echo "controller" > /etc/hostname cat > /etc/hosts << EOF 127.0.0.1 localhost 127.0.1.1 controller {put_eth0_ip_here} controller # The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters EOF Configure the network Setup the network in Native OpenStack VM # NOTE: The current IP is statically assigned by our system. Please do not change it. vi /etc/network/interfaces # This file describes the network interfaces available on your system # and how to activate them. For more information, see interfaces(5). # The loopback network interface auto lo iface lo inet loopback auto eth0 iface eth0 inet static address 192.168.8.210 netmask 255.255.255.0 gateway 192.168.8.1 dns-nameservers 192.168.8.15 8.8.8.8 # 需在此配置DNS,不可直接修改/etc/resolv.conf文件 auto eth1 iface eth1 inet static address 192.168.8.211 netmask 255.255.255.0 auto eth2 iface eth2 inet static address 192.168.8.212 netmask 255.255.255.0 Restart the network service /etc/init.d/networking restart Enable IP forwarding # To permit IP packets pass through different networks,# the network card should be configured with routing capability. echo"net.ipv4.ip_forward = 1">>/etc/sysctl.conf sysctl -p Upgrade your system to the latest version Add software repository echo -en 'deb http://ubuntu-cloud.archive.canonical.com/ubuntu precise-updates/havana main\n deb-src http://ubuntu-cloud.archive.canonical.com/ubuntu precise-updates/havana main' \ >> /etc/apt/sources.list.d/havana.list Upgrade the system apt-get update && apt-get dist-upgrade Install NTP Install the package apt-get install -y ntp Update /etc/ntp.conf file # Here we set ntp.ubuntu.com as the direct source of time.# You will also find that a local time source # is also provided in case of internet time service interruption. sed -i 's/server ntp.ubuntu.com/ \ server ntp.ubuntu.com \ server 127.127.1.0 \ fudge 127.127.1.0 stratum 10/g' /etc/ntp.conf Restart NTP service service ntp restart Set the OpenStack installation environment # Create the environment variables cat > /root/novarc << EOF export OS_TENANT_NAME=admin export OS_USERNAME=admin export OS_PASSWORD=password export MYSQL_PASS=password export SERVICE_PASSWORD=password export RABBIT_PASSWORD=password export FIXED_RANGE=10.0.0.0/24 export FLOATING_RANGE=$(/sbin/ifconfig eth0 | awk '/inet addr/ {print $2}' \ | cut -f2 -d ":" | awk -F "." '{print $1"."$2"."$3}').224/27 export OS_AUTH_URL="http://localhost:5000/v2.0/" export SERVICE_ENDPOINT="http://localhost:35357/v2.0" export SERVICE_TOKEN=stackinsider export MASTER="$(/sbin/ifconfig eth0 \ | awk '/inet addr/ {print $2}' | cut -f2 -d ":")" export LOCAL_IP="$(/sbin/ifconfig eth1 \ | awk '/inet addr/ {print $2}' | cut -f2 -d ":")" EOF # Update the global environment variables.cat/root/novarc >>/etc/profile source /etc/profile MySQL Server Setup the MySQL password for administrator cat << MYSQL_PRESEED | debconf-set-selections mysql-server-5.5 mysql-server/root_password password $MYSQL_PASS mysql-server-5.5 mysql-server/root_password_again password $MYSQL_PASS mysql-server-5.5 mysql-server/start_on_boot boolean true MYSQL_PRESEED Install the packages apt-get -y install mysql-server python-mysqldb curl Allow external connections # Bind MySQL service to all network interfaces. sed-i 's/127.0.0.1/0.0.0.0/g' /etc/mysql/my.cnf Restart MySQL service service mysql restart Create Databases, Users, Privileges for OpenStack mysql -uroot -p$MYSQL_PASS << EOF CREATE DATABASE nova; GRANT ALL PRIVILEGES ON nova.* TO 'nova'@'%' IDENTIFIED BY '$MYSQL_PASS'; GRANT ALL PRIVILEGES ON nova.* TO 'nova'@'localhost' IDENTIFIED BY '$MYSQL_PASS'; GRANT ALL PRIVILEGES ON nova.* TO 'nova'@'controller' IDENTIFIED BY '$MYSQL_PASS'; CREATE DATABASE glance; GRANT ALL PRIVILEGES ON glance.* TO 'glance'@'%' IDENTIFIED BY '$MYSQL_PASS'; GRANT ALL PRIVILEGES ON glance.* TO 'glance'@'localhost' IDENTIFIED BY '$MYSQL_PASS'; GRANT ALL PRIVILEGES ON glance.* TO 'glance'@'controller' IDENTIFIED BY '$MYSQL_PASS'; CREATE DATABASE keystone; GRANT ALL PRIVILEGES ON keystone.* TO 'keystone'@'%' IDENTIFIED BY '$MYSQL_PASS'; GRANT ALL PRIVILEGES ON keystone.* TO 'keystone'@'localhost' IDENTIFIED BY '$MYSQL_PASS'; GRANT ALL PRIVILEGES ON keystone.* TO 'keystone'@'controller' IDENTIFIED BY '$MYSQL_PASS'; CREATE DATABASE cinder; GRANT ALL PRIVILEGES ON cinder.* TO 'cinder'@'%' IDENTIFIED BY '$MYSQL_PASS'; GRANT ALL PRIVILEGES ON cinder.* TO 'cinder'@'localhost' IDENTIFIED BY '$MYSQL_PASS'; GRANT ALL PRIVILEGES ON cinder.* TO 'cinder'@'controller' IDENTIFIED BY '$MYSQL_PASS'; CREATE DATABASE neutron; GRANT ALL PRIVILEGES ON neutron.* TO 'neutron'@'%' IDENTIFIED BY '$MYSQL_PASS'; GRANT ALL PRIVILEGES ON neutron.* TO 'neutron'@'localhost' IDENTIFIED BY '$MYSQL_PASS'; GRANT ALL PRIVILEGES ON neutron.* TO 'neutron'@'controller' IDENTIFIED BY '$MYSQL_PASS'; FLUSH PRIVILEGES; EOF Message Queue Server: RabbitMQ Install the packages # Install the messaging queue server. Typically it is RabbitMQ. apt-get-yinstallrabbitmq-server Change the default password rabbitmqctl change_password guest $RABBIT_PASSWORD OpenStack Identity Server: Keystone Install the packages apt-get -y install keystone Update /etc/keystone/keystone.conf sed -i -e " s/# admin_token = ADMIN/admin_token = $SERVICE_TOKEN/g; \ s/# bind_host = 0.0.0.0/bind_host = 0.0.0.0/g; \ s/# public_port = 5000/public_port = 5000/g; \ s/# admin_port = 35357/admin_port = 35357/g; \ s/# compute_port = 8774/compute_port = 8774/g; \ s/# verbose = True/verbose = True/g; \ s/# idle_timeout/idle_timeout/g" /etc/keystone/keystone.conf Update MySQL connection for Keyatone sed -i '/connection = .*/{s|sqlite:///.*|mysql://'"keystone"':'"$MYSQL_PASS"'@'"$MASTER"'/keystone|g}'\ /etc/keystone/keystone.conf Restart Keystone and Sync database service keystone restart keystone-manage db_sync Create users, tenants, services for OpenStack wget http://wiki.stackinsider.com/images/9/99/Ksdata.sh_.txt -O Ksdata.sh sed -i 's/quantum/neutron/g' Ksdata.sh sed -i 's/QUANTUM/NEUTRON/g' Ksdata.sh sh Ksdata.sh Create endpoints for OpenStack wget http://wiki.stackinsider.com/images/1/18/Ksendpoints.sh_.txt -O Ksendpoints.sh sed -i 's/quantum/neutron/g' Ksendpoints.sh sh Ksendpoints.sh OpenStack Image Server: Glance Install the packages apt-get -y install glance Update the credentials for Glance sed -i -e " s/%SERVICE_TENANT_NAME%/service/g; \ s/%SERVICE_USER%/glance/g; s/%SERVICE_PASSWORD%/$SERVICE_PASSWORD/g; \ " /etc/glance/glance-api.conf /etc/glance/glance-registry.conf Update MySQL connection for Glance sed -i '/sql_connection = .*/{s|sqlite:///.*|mysql://'"glance"':'"$MYSQL_PASS"'@'"$MASTER"'/glance|g}'\ /etc/glance/glance-registry.conf /etc/glance/glance-api.conf Setup notifier for Glance sed -i " s/notifier_strategy = noop/notifier_strategy = rabbit/g;\ s/rabbit_password = guest/rabbit_password = $RABBIT_PASSWORD/g;" \ /etc/glance/glance-api.conf Setup flavor for Glance cat << EOF >>/etc/glance/glance-api.conf flavor = keystone+cachemanagement EOF cat << EOF >>/etc/glance/glance-registry.conf flavor = keystone EOF Restart Glance services service glance-api restart service glance-registry restart Sync Glance database glance-manage db_sync Download Cirros image wget https://launchpad.net/cirros/trunk/0.3.0/+download/cirros-0.3.0-x86_64-disk.img Upload Cirros image to Glance glance add name=cirros-0.3.0-x86_64 is_public=truecontainer_format=bare \ disk_format=qcow2 </root/cirros-0.3.0-x86_64-disk.img Check the image # Check the image ID to confirm if Glance operates normally. glance index OpenStack Block Storage: Cinder Install the packages apt-get install -y cinder-api cinder-scheduler cinder-volume iscsitarget \ open-iscsi iscsitarget-dkms python-cinderclient Prepare the logical volumnes for Cinder You can manage Cinder via a pre-prepared logical volumes "cinder-volumes", the size of which is 1.2GB. fdisk -l pvcreate /dev/vdb vgcreate cinder-volumes /dev/vdb Volume group "cinder-volumes" successfully created iSCSI configuration Enable the iSCSI target service sed -i 's/false/true/g'/etc/default/iscsitarget Re-configure the kernel modules dpkg-reconfigure iscsitarget-dkms Restart iSCSI services service iscsitarget restart && service open-iscsi restart Update the configuration file of Cinder cat >/etc/cinder/cinder.conf <<EOF [DEFAULT] sql_connection = mysql://cinder:$MYSQL_PASS@$MASTER/cinder rootwrap_config = /etc/cinder/rootwrap.conf api_paste_confg = /etc/cinder/api-paste.ini iscsi_helper = tgtadm volume_name_template = volume-%s volume_group = cinder-volumes verbose = True auth_strategy = keystone state_path = /var/lib/cinder lock_path = /var/lock/cinder volumes_dir = /var/lib/cinder/volumes rabbit_password = $RABBIT_PASSWORD EOF Update the credentials of Cinder sed -i -e " s/%SERVICE_TENANT_NAME%/service/g; \ s/%SERVICE_USER%/cinder/g; s/%SERVICE_PASSWORD%/$SERVICE_PASSWORD/g; " \ /etc/cinder/api-paste.ini Synchronize the database of Cinder cinder-manage db sync Restart the services of Cinder service cinder-api restart service cinder-scheduler restart service cinder-volume restart OpenStack Network Server: Neutron Install the Open vSwitch apt-get install -y openvswitch-switch apt-get install module-assistant module-assistant auto-install openvswitch-datapath 若遇kernel-header错误,则执行以下命令,再执行上一步命令即可: ln -s /usr/src/linux-headers-`uname -r`/include/generated/uapi/linux/version.h /lib/modules/`uname -r`/build/include/linux/ Configure the network bridge Configure the bridge for internal communication ovs-vsctl add-br br-int Configure the bridge for external communication ovs-vsctl add-br br-eth2 # Enable external network access under nested Open vSwitchifconfig br-eth2 promisc up Bind eth2 to the external bridge ovs-vsctl add-port br-eth2 eth2 Update the external bridge configuration vim /etc/network/interfaces # Modify the corresponding configuration auto eth2 iface eth2 inet manual up ifconfig$IFACE 0.0.0.0 up up ip linkset$IFACE promisc on down ip linkset$IFACE promisc off down ifconfig$IFACE down auto br-eth2 iface br-eth2 inet static address {put_eth2_ip_here}netmask 255.255.255.0 up ip linkset$IFACE promisc on down ip linkset$IFACE promisc off Restart the network service /etc/init.d/networking restart Install Neutron apt-get -y install neutron-server python-cliff \ neutron-plugin-openvswitch-agent \ neutron-dhcp-agent python-pyparsing Configure the RabbitMQ sed -i -e " s/# auth_strategy/auth_strategy/g; \ s/# fake_rabbit/fake_rabbit/g; \ s/# rabbit_host = localhost/rabbit_host = $MASTER/g; \ s/# rabbit_password = guest/rabbit_password = $RABBIT_PASSWORD/g"/etc/neutron/neutron.conf Configure the Neutron Update the general configuration for Neutron cat << EOF >>/etc/neutron/plugins/openvswitch/ovs_neutron_plugin.ini [securitygroup] firewall_driver = neutron.agent.linux.iptables_firewall.OVSHybridIptablesFirewallDriver [database]connection=mysql://neutron:$MYSQL_PASS@$MASTER/neutron [ovs] network_vlan_ranges = physnet1 bridge_mappings = physnet1:br-eth2 EOF Update the MySQL connection for Neutron sed -i '/connection = .*/{s|sqlite:///.*|mysql://'"neutron"':'"password"'@'"$MASTER"'/neutron|g}' \/etc/neutron/neutron.conf Update the metadata agent for Neutron sed -i -e " s/%SERVICE_TENANT_NAME%/service/g; s/%SERVICE_USER%/neutron/g; \ s/%SERVICE_PASSWORD%/$SERVICE_PASSWORD/g; "/etc/neutron/metadata_agent.ini Update the credentials for Neutron sed -i -e " s/%SERVICE_TENANT_NAME%/service/g; s/%SERVICE_USER%/neutron/g; \ s/%SERVICE_PASSWORD%/$SERVICE_PASSWORD/g; "/etc/neutron/neutron.conf Change the passphase of Neutron metadata agent sed -i -e " s/# metadata_proxy_shared_secret =/metadata_proxy_shared_secret \ = helloStackinsider/g; "/etc/neutron/metadata_agent.ini Change the passphase of Neutron dhcp agent sed -i -e " s/# interface_driver = neutron.agent.linux.interface.OVSInterfaceDriver/interface_driver = \ neutron.agent.linux.interface.OVSInterfaceDriver/g; "/etc/neutron/dhcp_agent.ini Restart the Neutron services cd /etc/init.d/; for i in $(ls neutron-*); do sudo service $i restart; done OpenStack Controller Server: Nova Controller Install the packages apt-get -y install nova-api nova-cert nova-common pm-utils nova-conductor \ nova-scheduler python-nova python-novaclient nova-consoleauth novnc nova-novncproxy Configure Nova Update the credential for Nova sed -i -e " s/127.0.0.1/$MASTER/g; s/%SERVICE_TENANT_NAME%/service/g; \ s/%SERVICE_USER%/nova/g; s/%SERVICE_PASSWORD%/$SERVICE_PASSWORD/g; " \ /etc/nova/api-paste.ini Update the general configuration: /etc/nova/nova.conf cat >/etc/nova/nova.conf <<EOF [DEFAULT] # MySQL Connection # sql_connection=mysql://nova:$MYSQL_PASS@$MASTER/nova # nova-scheduler # rabbit_host=$MASTER rabbit_password=$RABBIT_PASSWORD #scheduler_driver=nova.scheduler.simple.SimpleScheduler #compute_scheduler_driver=nova.scheduler.filter_scheduler.FilterScheduler compute_scheduler_driver=nova.scheduler.simple.SimpleScheduler # nova-api # cc_host=$MASTER auth_strategy=keystone s3_host=$MASTER ec2_host=$MASTER nova_url=http://$MASTER:8774/v1.1/ ec2_url=http://$MASTER:8773/services/Cloud keystone_ec2_url=http://$MASTER:5000/v2.0/ec2tokens api_paste_config=/etc/nova/api-paste.ini allow_admin_api=true use_deprecated_auth=false ec2_private_dns_show_ip=True dmz_cidr=169.254.169.254/32 ec2_dmz_host=169.254.169.254 metadata_host=$MASTER metadata_listen=0.0.0.0 enabled_apis=ec2,osapi_compute,metadata # Networking # network_api_class=nova.network.neutronv2.api.API neutron_url=http://$MASTER:9696 neutron_auth_strategy=keystone neutron_admin_tenant_name=service neutron_admin_username=neutron neutron_admin_password=$SERVICE_PASSWORD neutron_admin_auth_url=http://$MASTER:35357/v2.0 libvirt_vif_driver=nova.virt.libvirt.vif.LibvirtHybridOVSBridgeDriver linuxnet_interface_driver=nova.network.linux_net.LinuxOVSInterfaceDriver firewall_driver=nova.virt.libvirt.firewall.IptablesFirewallDriver #Metadata service_neutron_metadata_proxy = True neutron_metadata_proxy_shared_secret = helloStackinsider # Compute # compute_driver=libvirt.LibvirtDriver # Cinder # volume_api_class=nova.volume.cinder.API # Glance # glance_api_servers=$MASTER:9292 image_service=nova.image.glance.GlanceImageService # novnc # novnc_enable=true novncproxy_base_url=http://$MASTER:6080/vnc_auto.html vncserver_proxyclient_address=$MASTER vncserver_listen=$MASTER # Misc # logdir=/var/log/nova state_path=/var/lib/nova lock_path=/var/lock/nova #root_helper=sudo nova-rootwrap /etc/nova/rootwrap.conf rootwrap_config=/etc/nova/rootwrap.conf verbose=true #verbose=false EOF Synchronize Nova database nova-manage db sync Restart Nova services cd /etc/init.d/; for i in $( ls nova-* ); do sudo service $i restart; done OpenStack Compute Server: Nova Compute Install the Hypervisor apt-get install -y kvm libvirt-bin pm-utils Setup Cgroup support for libvirt cat << EOF >>/etc/libvirt/qemu.conf cgroup_device_acl = ["/dev/null", "/dev/full", "/dev/zero","/dev/random", "/dev/urandom","/dev/ptmx", "/dev/kvm", "/dev/kqemu","/dev/rtc", "/dev/hpet","/dev/net/tun", ] EOF Allow Live Migration sed -i '/#listen_tls/s/#listen_tls/listen_tls/;/#listen_tcp/s/#listen_tcp/listen_tcp/;/#auth_tcp/s/#auth_tcp/auth_tcp/; /auth_tcp/s/sasl/none/' \/etc/libvirt/libvirtd.conf Listen on TCP sed -i '/env libvirtd_opts/s/-d/-d -l/'/etc/init/libvirt-bin.conf sed -i '/libvirtd_opts/s/-d/-d -l/'/etc/default/libvirt-bin Restart libvirt-bin service service libvirt-bin restart Install the Nova Compute apt-get -yinstallnova-compute-kvm Modify the libvirt_type vi /etc/nova/nova-compute.conf libvirt_type=kvm 修改为 libvirt_type=qemu Restart Nova services cd /etc/init.d/; for i in $( ls nova-* ); do sudo service $i restart; done OpenStack Dashboard: Horizon Install Horizon apt-get -y install apache2 libapache2-mod-wsgi openstack-dashboard memcached python-memcache Prepare Tenant Network Create a bash script for preparation vi /root/prepare_network.sh #!/bin/bash # Create Tenant and User # tenant=TenantA user=UserA usermail=usera@stackinsider.com role=Member if keystone tenant-list | grep -q $tenant;then echo "Tenant $tenant existed!" else tenant_id=`keystone tenant-create --name $tenant | awk '/id/{print $4}'` fi if keystone user-list | grep -q $user;then echo "User $user existed!" else keystone user-create --name=$user --pass=password --tenant-id $tenant_id --email=$usermail fi keystone user-role-add --tenant $tenant --user $user --role $role # Create virtual router and sub-network # neutron net-create --tenant-id ${tenant_id} sharednet1 --shared --provider:network_type flat \ --provider:physical_network physnet1 neutron subnet-create --tenant-id ${tenant_id} sharednet1 192.168.100.0/24 --no-gateway \ --allocation-pool start=192.168.100.150,end=192.168.100.200 # 新建子网,配置共享网段 Execute the bash script to create network interconnection bash prepare_network.sh Set up the default security group rules # Obtain TenantA's default security group ID neutron --os-tenant-name TenantA --os-username UserA --os-password password --os-auth-url=http://localhost:5000/v2.0 security-group-list # Enable ICMP and TCP ports neutron security-group-rule-create --protocol icmp --direction ingress {TenantA security group ID} neutron security-group-rule-create --protocol icmp --direction egress {TenantA security group ID} neutron security-group-rule-create --protocol tcp --direction egress --port-range-min 1 --port-range-max 65535 {TenantA security group ID} neutron security-group-rule-create --protocol tcp --direction ingress --port-range-min 1 --port-range-max65535{TenantA security group ID} Start a VM Check the Ubuntu image # Check the image ID to confirm if Glance operates normally. glance index Generate ssh key and Upload it to Nova # Generate ssh key ssh-keygen # Upload ssh pub key to nova nova keypair-add key01 --pub-key~ /.ssh /id_rsa.pub Launch a VM nova --os-tenant-name TenantA --os-username UserA --os-password password --os-auth-url=http://localhost:5000/v2.0 boot --flavor 1 --image{the cirros ID from Glance} --security_group default --key-name key01 vm001 Check the VM status # Check your VM status nova --os-tenant-name TenantA --os-username UserA --os-password password \ --os-auth-url=http://localhost:5000/v2.0 list Access the VM instance using its flat IP # Obtain the VM's fixed IP nova --os-tenant-name TenantA --os-username UserA --os-password password \ --os-auth-url=http://localhost:5000/v2.0 list # You can find its fixed IP in the "Networks" section: sharednet1={flat IP}.# SSH to your VM when your VM is ACTIVEssh cirros@{put_flat_ip_here} Access the Dashboard http://controller/horizon(controller为主机名) Questions 执行“neutron--os-tenant-nameTenantA--os-usernameUserA--os-passwordpassword--os-auth-url=http://localhost:5000/v2.0 security-group-list”出现错误: “404 Not Found.The resource could not be found.” 解决: vi /etc/neutron/plugins/openvswitch/ovs_neutron_plugin.ini [securitygroup] # Firewall driver for realizing neutron security group function. # firewall_driver = neutron.agent.firewall.NoopFirewallDriver firewall_driver = neutron.agent.linux.iptables_firewall.OVSHybridIptablesFirewallDriver 然后重启neutron服务: cd /etc/init.d/; for i in $( ls neutron-* ); do sudo service $i restart; done 本文转自 xxrenzhe11 51CTO博客,原文链接:http://blog.51cto.com/xxrenzhe/1351626,如需转载请自行联系原作者

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

通过Docker搭建开源版IVRE

1 引言 1.1 编写目的 本文主要介绍开源IVRE项目的安装、部署和配置。目的是提供给IVRE项目学习、研究人员,利于他们更快的搭建和部署IVRE。 1.2 背景 IVRE(又名DRUNK)是一款网络侦查框架,包括两个基于p0f和Bro的被动侦查模块和一个基于Nmap&Zmap的主动侦查模块,其功能类似于国内知道创宇公司推出的一款网络空间搜索引擎ZoomEye(钟馗之眼)。 1.3 定义 Docker:一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化。容器是完全使用沙箱机制,相互之间不会有任何接口(类似 iPhone 的 app)。几乎没有性能开销,可以很容易地在机器和数据中心中运行。最重要的是,他们不依赖于任何语言、框架包括系统。 1.4 参考资料 安装Docker: http://www.cnblogs.com/MicroTeam/p/see-docker-run-in-debian-with-aliyun-ecs.html IVRE官方网站: https://ivre.rocks/ GitHub https://github.com/cea-sec/ivre 2 系统配置 2.1 运行环境 Ubuntu Server 14.4 64位 Docker IVRE 2.2 系统依赖 Python 2, version 2.6 minimum the Crypto module the pymongo module, version 2.7.2 minimum. Nmap & ZMap Bro & p0f MongoDB, version 2.6 minimum web服务器(在Apache、Nginx下测试通过) web浏览器(在FireFox和Chromum下测试通过) Maxmind GeoIP免费数据库 Tesseract(可选,可对Nmap扫描结果增加快照) Docker & Vagrant (version 1.6 minimum,可选) 2.3 前端组件 AngularJS Twitter Bootstrap jQuery D3.js flag-icon-css Passive recon 2.4 系统安装部署图 2.5 系统硬件配置 测试机配置: CPU:Intel至强E5400系列CPU*2 内存:4G 1333MHz 硬盘:100GB 2.6 系统应用服务器软件安装与配置 Linux服务器安装步骤(略) 注意:内核版本如果低于 3.8,就要升级内核,参考方法如下 http://docs.docker.com/installation/debian/ 查看linux内核命令: uname –a 3 程序部署 3.1 安装Docker 快速安装Docker方法有2种: 第一种方法:(推荐使用) sudowget-qO-https://get.docker.com/|sh 第二种方法: sudocurl-sSLhttps://get.docker.com/|sh 3.1.1 验证Docker安装是否成功(可忽略) 运行 hello world: sudodockerrunhello-world 如果前面步骤都没有问题的话,能看到 hello-world 启动了。 HellofromDocker. Thismessageshowsthatyourinstallationappearstobeworkingcorrectly. 3.1.2 把非管理员用户添加到docker组 sudo useradd -G docker 登陆系统用户名 3.2 安装Vagrant 安装IVRE方法有2种: 第一种方法:(推荐使用) wgethttps://releases.hashicorp.com/vagrant/1.7.4/vagrant_1.7.4_x86_64.deb sudodpkg-ivagrant_1.7.4_x86_64.deb 第二种方法: sudoapt-getinstall-yvagrant 3.3 安装IVRE $mkdir-m1777var_lib_mongodbvar_log_mongodbivre-share $wget-qhttps://ivre.rocks/Vagrantfile $sudovagrantup--no-parallel $dockerattachivreclient root@e809cb41cb9a:/# 此时IVRE已经安装成功。通过Docker装好的IVRE是没有数据的。 界面如下: 4 IVRE运行和停止 查看docker有那些容器,命令: dockerps–a 开启IVRE分三步, 第一步要开启database server,命令: sudodockerstartivredb 第二步开启web,命令: sudodockerstartivreweb 第三步开启客户端,命令: sudodockerstartivreclient 然后通过attach命令进入ivreclient sudodockerattachivreclient 5 IVRE扫描并导入数据 通过attach命令进入ivreclient sudodockerattachivreclient 5.1运行如下初始化命令:(前4步可忽略) root@881486651a32:/$ipinfo--init Thiswillremoveanypassiveinformationinyourdatabase.Process?[y/N]y root@881486651a32:/$ipdata--init Thiswillremoveanycountry/ASinformationinyourdatabase.Process?[y/N]y root@881486651a32:/$scancli--init Thiswillremoveanyscanresultinyourdatabase.Process?[y/N]y root@881486651a32:/$runscans-agentdb--init Thiswillremoveanyagentand/orscaninyourdatabaseandfiles.Process?[y/N]y root@881486651a32:/$ipdata--download--import-all--dont-feed-ipdata-cols [...] Thelatestcommandwilltakealongtime.Thenwecanintegratethe Nmapresultstothedatabase: root@881486651a32:/$nmap2db-r-sMySource-cMyCategory/ivre-share Youcanthenexittheshell(`C-d`),thiswillstopthe container. 或者忽略5.1步骤执行如下命令: root@881486651a32:/$ipdata--download 5.1 扫描任务 执行命令: root@881486651a32:/$runscans--routable--limit1000--output=XMLFork 上面这条命令将对互联网上1000个随机主机进行标准扫描,开启13个nmap进程。 5.2 扫描结果入库 root@881486651a32:/$nmap2db-cROUTABLE-CAMPAIGN-001-sMySource-rscans/ROUTABLE/up 5.3 界面展示 6 安装出错解决 安装IVRE成功后,通过attach命令进入ivreclient后。可能出现缺少ipdata、runscans和nmap2db等命令现象。 解决方法如下: 通过attach命令进入ivreclient sudodockerattachivreclient 安装curl root@881486651a32:/$apt-getinstallcrul 安装unzip root@881486651a32:/$apt-getinstallunzip 利用curl命令将IVRE项目里的bin目录下所有文件下载到Docker容器里: root@881486651a32:/$tmp root@881486651a32:/$curl–Ohttp://hackliu.com/bin.zip root@881486651a32:/$cd/ 将bin.zip解压到/usr/bin目录 root@881486651a32:/$unzip/tmp/bin.zip–d/usr/ 为下载的文件添加执行权限: root@881486651a32:/$chmod+xanalyzercli root@881486651a32:/$chmod+xgetmoduli root@881486651a32:/$chmod+xhttpd-ivre root@881486651a32:/$chmod+xipdata root@881486651a32:/$chmod+xipinfo root@881486651a32:/$chmod+xipinfohost root@881486651a32:/$chmod+xnmap2db root@881486651a32:/$chmod+xp0f2db root@881486651a32:/$chmod+xpassiverecon2db root@881486651a32:/$chmod+xpassivereconworker root@881486651a32:/$chmod+xplotdb root@881486651a32:/$chmod+xrunscans root@881486651a32:/$chmod+xrunscans-agent root@881486651a32:/$chmod+xrunscans-agentdb root@881486651a32:/$chmod+xscancli root@881486651a32:/$chmod+xscanstatus 7 其他 7.1 安装所需软件包 链接: http://pan.baidu.com/s/1kUsuOGv 密码: wvct 本文作者:HackLiu 来源:51CTO

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

《Hadoop实战第2版》——导读

目 录 前 言第1章 Hadoop简介1.1 什么是Hadoop1.2 Hadoop项目及其结构1.3 Hadoop体系结构1.4 Hadoop与分布式开发1.5 Hadoop计算模型—MapReduce1.6 Hadoop数据管理1.7 Hadoop集群安全策略1.8 本章小结第2章 Hadoop的安装与配置2.1 在Linux上安装与配置Hadoop2.2 在Mac OSX上安装与配置Hadoop2.3 在Windows上安装与配置Hadoop2.4 安装和配置Hadoop集群2.5 日志分析及几个小技巧2.6 本章小结第3章 MapReduce计算模型3.1 为什么要用MapReduce3.2 MapReduce计算模型3.3 MapReduce任务的优化3.4 Hadoop流3.5 Hadoop Pipes3.6 本章小结

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

Android版-微信APP支付

欢迎留言、转发 文章首发地址:http://www.jianshu.com/p/febf7c2eea82 微信极速开发系列文章(微信支付、授权获取用户信息等):点击这里 目录 1、注册账号、开发者认证 2、添加应用 3、申请微信支付 4、技术开发功能实现步骤介绍 5、代码实例 服务端源码地址:http://git.oschina.net/javen205/weixin_guide 客户端源码地址:https://github.com/Javen205/JPay 微信APP支付接入商户服务中心 官方介绍文档 1、注册账号、开发者认证 在开放平台直接注册,注册邮箱不能与微信其他的产品同号。 比较坑的是微信公众号中的支付(微信买单、刷卡、公众号支付、wap支付)以及微信app支付都需要进行微信认证而不是公用一个微信商户平台(需要交两次认证的费用)。 微信认证这个时间比较短(毕竟交了300大洋)一般一个工作日就会有人联系你核查公司的资料。 微信认证(开发者资质认证)通过之后就可以在开放平台添加应用了(这个需要审核),应用通过之后就可以申请微信支付了(也需要审核) 2、添加应用 这个比较简单,按照提示操作就行 上图 应用包名只定义,应用签名可以使用资源下载中心的签名生成工具。务必记住包名以及签名keystore文件的密码,如果包名或者签名文件不对打包是唤不起微信支付的。 3、申请微信支付 如果添加的应用审核通过了(一个工作日),就可以直接申请微信支付了(7个工作日之内)。 审核通过之后将会收到审核通过的邮件,里面有登录商户平台的登录账户、密码、商户号以及一些操作指引的说明。服务端生成预付订单的签名需要密钥 设置方法可以参考这里 4、技术开发功能实现 微信APP支付介绍【文档】 APP端开发步骤说明 【文档】 这里主要聊聊Android微信支付,主要包括以下几个步骤 1、商户服务端生成订单并在微信平台生成预付订单 2、客户端调起微信支付进行支付 3、客户端回调支付结果 4、服务端接收支付通知 1、商户服务端生成订单并在微信平台生成预付订单 调起微信支付前需要服务器生成支付订单再调用【统一下单API】生成预付订单prepayId,再生成签名sign【调起支付API】 以上两个步骤建议都在服务端完成,客户端(Android)通过接口获取对应的参数即可 2、客户端调起微信支付进行支付 通过微信提供的jar 唤起微信支付 3、客户端回调支付结果 参照微信SDK Sample,在net.sourceforge.simcpux.wxapi包路径中实现WXPayEntryActivity类【包名或类名不一致会造成无法回调】 栗子说明:认真反复读了几遍,感觉这句话有歧义是一个坑,测试的时候一直不回调。这里他想说的意识如下: 比如你申请应用包名为:javen.com 那么回调的WXPayEntryActivity类必须放到javen.com.wxapi 的包下面 4、服务端接收支付通知 支付结果通知【官方文档】 代码实现参考开源项目 【点击这里】 5、代码实例 服务端代码:根据商户订单生成微信预付订单并返回唤起微信支付需要的参数。Demo中参数写成固定了仅供参考 此项目已开源 【点击这里】 如果对你有帮助请点击Start告诉我 hahaha 。以下代码对应的目录在 com.javen.weixin.controller.WeixinPayController.java中 /** * 微信APP支付 */ public void appPay(){ //不用设置授权目录域名 //统一下单地址 https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1# Map<String, String> params = new HashMap<String, String>(); params.put("appid", appid); params.put("mch_id", partner); params.put("nonce_str", System.currentTimeMillis() / 1000 + ""); params.put("body", "Javen微信公众号极速开发"); String out_trade_no=System.currentTimeMillis()+""; params.put("attach", "custom json"); params.put("out_trade_no", out_trade_no); int price=10000; params.put("total_fee", price+""); String ip = IpKit.getRealIp(getRequest()); if (StrKit.isBlank(ip)) { ip = "127.0.0.1"; } params.put("spbill_create_ip", ip); params.put("notify_url", notify_url); params.put("trade_type", "APP"); String sign = PaymentKit.createSign(params, paternerKey); params.put("sign", sign); String xmlResult = PaymentApi.pushOrder(params); System.out.println(xmlResult); Map<String, String> result = PaymentKit.xmlToMap(xmlResult); String return_code = result.get("return_code"); String return_msg = result.get("return_msg"); if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) { ajax.addError(return_msg); renderJson(ajax); return; } String result_code = result.get("result_code"); if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) { ajax.addError(return_msg); renderJson(ajax); return; } // 以下字段在return_code 和result_code都为SUCCESS的时候有返回 String prepay_id = result.get("prepay_id"); //封装调起微信支付的参数 https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12 Map<String, String> packageParams = new HashMap<String, String>(); packageParams.put("appid", appid); packageParams.put("partnerid", partner); packageParams.put("prepayid", prepay_id); packageParams.put("package", "Sign=WXPay"); packageParams.put("noncestr", System.currentTimeMillis() + ""); packageParams.put("timestamp", System.currentTimeMillis() / 1000 + ""); String packageSign = PaymentKit.createSign(packageParams, paternerKey); packageParams.put("sign", packageSign); String jsonStr = JsonUtils.toJson(packageParams); System.out.println("最新返回apk的参数:"+jsonStr); renderJson(jsonStr); } 客户端代码实现 使用单例模式统一入口,首先判断微信客户端是否安装,如果有安装再从商户服务器获取调起支付的参数 public class IPay { private static IPay mIPay; private Context mContext; private IPay(Context context) { mContext = context; } public static IPay getIntance(Context context){ if (mIPay == null) { synchronized(IPay.class){ if (mIPay == null) { mIPay = new IPay(context); } } } return mIPay; } //支付结果回调 public interface IPayListener{ void onPay(int code); } public void toTestPay(Order order,IPayListener listener){ if (order != null) { if (IPayLogic.getIntance(mContext.getApplicationContext()).isWeixinAvilible()) { Constants.payListener = listener; new TestPayPrepay(mContext).execute(); }else { Toast.makeText(mContext, "未安装微信", Toast.LENGTH_LONG).show(); } }else { Toast.makeText(mContext, "参数异常 order is null", Toast.LENGTH_LONG).show(); } } } 调起微信支付、获取调取微信支付参数、判断微信是否安装逻辑实现 public class IPayLogic { private static IPayLogic mIPayLogic; private Context mContext; private IPayLogic(Context context) { mContext = context; } public static IPayLogic getIntance(Context context){ if (mIPayLogic == null) { synchronized(IPayLogic.class){ if (mIPayLogic == null) { mIPayLogic = new IPayLogic(context); } } } return mIPayLogic; } //测试 public String testPay(){ return HttpKit.get(Constants.TESTPAY_URL); } /** * 调起支付 * @param appId * @param partnerId * @param prepayId * @param nonceStr * @param timeStamp * @param sign */ public void startWXPay(String appId,String partnerId,String prepayId, String nonceStr,String timeStamp,String sign){ IWXAPI api= WXAPIFactory.createWXAPI(mContext, null); api.registerApp(appId); boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT; if (!isPaySupported) { Toast.makeText(mContext, "请更新微信客户端", Toast.LENGTH_SHORT).show(); return; } PayReq request = new PayReq(); request.appId = appId; request.partnerId = partnerId; request.prepayId= prepayId; request.packageValue = "Sign=WXPay"; request.nonceStr=nonceStr; request.timeStamp= timeStamp; request.sign= sign; api.sendReq(request); } /** * 判断微信是否安装 * @param context * @return */ public boolean isWeixinAvilible() { final PackageManager packageManager = mContext.getPackageManager();// 获取packagemanager List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息 if (pinfo != null) { for (int i = 0; i < pinfo.size(); i++) { String pn = pinfo.get(i).packageName; if (pn.equals("com.tencent.mm")) { return true; } } } return false; } } HttpKit MD5 工具类 /** * HttpKit */ public class HttpKit { private HttpKit() {} /** * https 域名校验 */ private class TrustAnyHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; } } /** * https 证书管理 */ private class TrustAnyTrustManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } private static final String GET = "GET"; private static final String POST = "POST"; private static String CHARSET = "UTF-8"; private static final SSLSocketFactory sslSocketFactory = initSSLSocketFactory(); private static final TrustAnyHostnameVerifier trustAnyHostnameVerifier = new HttpKit().new TrustAnyHostnameVerifier(); private static SSLSocketFactory initSSLSocketFactory() { try { TrustManager[] tm = {new HttpKit().new TrustAnyTrustManager() }; SSLContext sslContext = SSLContext.getInstance("TLS"); // ("TLS", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); return sslContext.getSocketFactory(); } catch (Exception e) { throw new RuntimeException(e); } } public static void setCharSet(String charSet) { if (charSet.isEmpty()) { throw new IllegalArgumentException("charSet can not be blank."); } HttpKit.CHARSET = charSet; } private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { URL _url = new URL(url); HttpURLConnection conn = (HttpURLConnection)_url.openConnection(); if (conn instanceof HttpsURLConnection) { ((HttpsURLConnection)conn).setSSLSocketFactory(sslSocketFactory); ((HttpsURLConnection)conn).setHostnameVerifier(trustAnyHostnameVerifier); } conn.setRequestMethod(method); conn.setDoOutput(true); conn.setDoInput(true); conn.setConnectTimeout(19000); conn.setReadTimeout(19000); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); if (headers != null && !headers.isEmpty()) for (Entry<String, String> entry : headers.entrySet()) conn.setRequestProperty(entry.getKey(), entry.getValue()); return conn; } /** * Send GET request */ public static String get(String url, Map<String, String> queryParas, Map<String, String> headers) { HttpURLConnection conn = null; try { conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), GET, headers); conn.connect(); return readResponseString(conn); } catch (Exception e) { throw new RuntimeException(e); } finally { if (conn != null) { conn.disconnect(); } } } public static String get(String url, Map<String, String> queryParas) { return get(url, queryParas, null); } public static String get(String url) { return get(url, null, null); } /** * Send POST request */ public static String post(String url, Map<String, String> queryParas, String data, Map<String, String> headers) { HttpURLConnection conn = null; try { conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers); conn.connect(); OutputStream out = conn.getOutputStream(); out.write(data.getBytes(CHARSET)); out.flush(); out.close(); return readResponseString(conn); } catch (Exception e) { throw new RuntimeException(e); } finally { if (conn != null) { conn.disconnect(); } } } public static String post(String url, Map<String, String> queryParas, String data) { return post(url, queryParas, data, null); } public static String post(String url, String data, Map<String, String> headers) { return post(url, null, data, headers); } public static String post(String url, String data) { return post(url, null, data, null); } private static String readResponseString(HttpURLConnection conn) { StringBuilder sb = new StringBuilder(); InputStream inputStream = null; try { inputStream = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET)); String line = null; while ((line = reader.readLine()) != null){ sb.append(line).append("\n"); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } /** * Build queryString of the url */ private static String buildUrlWithQueryString(String url, Map<String, String> queryParas) { if (queryParas == null || queryParas.isEmpty()) return url; StringBuilder sb = new StringBuilder(url); boolean isFirst; if (url.indexOf("?") == -1) { isFirst = true; sb.append("?"); } else { isFirst = false; } for (Entry<String, String> entry : queryParas.entrySet()) { if (isFirst) isFirst = false; else sb.append("&"); String key = entry.getKey(); String value = entry.getValue(); if (!value.isEmpty()) try {value = URLEncoder.encode(value, CHARSET);} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);} sb.append(key).append("=").append(value); } return sb.toString(); } } public class MD5 { public static String MD5sign(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput = s.getBytes("UTF-8"); // 获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要 mdInst.update(btInput); // 获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str).toLowerCase(); } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) { System.out.println(MD5sign("Hello world")); } } 使用AsyncTask异步获取调起微信支付的相关参数。当然你也可以使用其他的异步网络请求开源框架 public class TestPayPrepay extends AsyncTask<Object, Integer, String> { private Context mContext; public TestPayPrepay(Context context) { this.mContext = context; } @Override protected String doInBackground(Object... params) { System.out.println("TestPayPrepay doInBackground"); return IPayLogic.getIntance(mContext).testPay(); } @Override protected void onPostExecute(String result) { try { if (result!=null) { System.out.println("TestPayPrepay result>"+result); JSONObject data = new JSONObject(result); if(!data.has("code")){ String sign = data.getString("sign"); String timestamp = data.getString("timestamp"); String noncestr = data.getString("noncestr"); String partnerid = data.getString("partnerid"); String prepayid = data.getString("prepayid"); String appid = data.getString("appid"); Toast.makeText(mContext, "正在调起支付", Toast.LENGTH_SHORT).show(); Constants.APP_ID = appid; IPayLogic.getIntance(mContext).startWXPay(appid, partnerid, prepayid, noncestr, timestamp, sign); }else{ String message = data.getString("message"); Log.d("PAY_GET", "返回错误"+message); Toast.makeText(mContext, "返回错误:"+message, Toast.LENGTH_SHORT).show(); } }else { System.out.println("get prepayid exception, is null"); } } catch (Exception e) { Log.e("PAY_GET", "异常:"+e.getMessage()); Toast.makeText(mContext, "异常:"+e.getMessage(), Toast.LENGTH_SHORT).show(); } super.onPostExecute(result); } } 支付结果回调 <activity android:name="[应用的包名].wxapi.WXPayEntryActivity" android:exported="true" android:theme="@android:style/Theme.Translucent" android:launchMode="singleTop" > </activity> 封装的是SDK 所以这里设置了一个透明的主题 public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler{ private IWXAPI api; private IPayListener payListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题 LinearLayout ll = new LinearLayout(this); setContentView(ll); api = WXAPIFactory.createWXAPI(this, Constants.APP_ID); api.handleIntent(getIntent(), this); finish(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); api.handleIntent(intent, this); } @Override public void onReq(BaseReq req) { } @Override public void onResp(BaseResp resp) { payListener = Constants.payListener; int code = resp.errCode; System.out.println("onResp errCode>"+code); if (payListener!=null) { payListener.onPay(code); System.out.println("payListener callback"); }else { System.out.println("payListener not callback"); } } } 注意:如果回调的code一直返回-1 1、请检查应用包名以及apk 的签名是否与你提交到微信开放平台的一致 2、请检查返回调取微信支付的参数是否正确 大部分原因是第一种 遗留问题:由于支付应用的包名不固定WXPayEntryActivity无法封装到jar中,需要单独在支付应用添加.wxapi 这个包名并复制 WXPayEntryActivity到此包中。如果有好的解决方案欢迎留言 微信开发系列文章 http://www.jianshu.com/p/a172a1b69fdd 推荐阅读 极速开发微信公众号之微信买单 极速开发微信公众号之公众号支付 极速开发微信公众号之扫码支付 极速开发微信公众号之刷卡支付 极速开发微信公众号之现金红包 极速开发微信公众号之模板消息 如果此文章对你有帮助请点击喜欢告诉我 服务端源码地址:http://git.oschina.net/javen205/weixin_guide 客户端源码地址:https://github.com/Javen205/JPay

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

Macaca-Java版入门指南

导语 接触Macaca已经有一段时间,从开始的对于UI自动化的调研开始,将Macaca与Appium,Robotium等自动化方案进行了多方对比,最终Macaca脱颖而出成为团队的敲定方案,随后经历了Macaca从JS版本到Java版本的迭代,踩了很多坑,积累了很多经验教训,在这里总结沉淀一下,以方便后来人少走弯路,加快脚步。 一、认识Macaca Macaca是一套基于WebDriver标准协议开发的开源自动化解决方案,旨在解决跨平台,跨终端的UI自动化测试的短板问题,减少繁杂、重复的人工工作,降低自动化测试的上手门坎。终端上,Macaca同时支持Native(iOS&&Android)、Hybrid、Mobile Web、以及PC端的自动化测试,用例编写上,Macaca采取CS架构,可以支持任意编程语言的封装,目前已

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

opencv 人脸识别 java版------2

代码下载地址http://download.csdn.net/detail/u013378306/9656546 1.环境搭建:见上一篇博客 整个项目的结构图: 2.编写DetectFaceDemo.java,代码如下: packagecom.njupt.zhb.test; importorg.opencv.core.Core; importorg.opencv.core.Mat; importorg.opencv.core.MatOfRect; importorg.opencv.core.Point; importorg.opencv.core.Rect; importorg.opencv.core.Scalar; importorg.opencv.highgui.Highgui; importorg.opencv.objdetect.CascadeClassifier; // //Detectsfacesinanimage,drawsboxesaroundthem,andwritestheresults //to"faceDetection.png". // publicclassDetectFaceDemo{ publicvoidrun(){ System.out.println("\nRunningDetectFaceDemo"); System.out.println(getClass().getResource("lbpcascade_frontalface.xml").getPath()); //Createafacedetectorfromthecascadefileintheresources //directory. //CascadeClassifierfaceDetector=newCascadeClassifier(getClass().getResource("lbpcascade_frontalface.xml").getPath()); //Matimage=Highgui.imread(getClass().getResource("lena.png").getPath()); //注意:源程序的路径会多打印一个‘/’,因此总是出现如下错误 /* *Detected0facesWritingfaceDetection.pnglibpngwarning:Image *widthiszeroinIHDRlibpngwarning:ImageheightiszeroinIHDR *libpngerror:InvalidIHDRdata */ //因此,我们将第一个字符去掉 StringxmlfilePath=getClass().getResource("lbpcascade_frontalface.xml").getPath().substring(1); CascadeClassifierfaceDetector=newCascadeClassifier(xmlfilePath); Matimage=Highgui.imread(getClass().getResource("we.jpg").getPath().substring(1)); //Detectfacesintheimage. //MatOfRectisaspecialcontainerclassforRect. MatOfRectfaceDetections=newMatOfRect(); faceDetector.detectMultiScale(image,faceDetections); System.out.println(String.format("Detected%sfaces",faceDetections.toArray().length)); //Drawaboundingboxaroundeachface. for(Rectrect:faceDetections.toArray()){ Core.rectangle(image,newPoint(rect.x,rect.y),newPoint(rect.x+rect.width,rect.y+rect.height),newScalar(0,255,0)); } //Savethevisualizeddetection. Stringfilename="faceDetection.png"; System.out.println(String.format("Writing%s",filename)); Highgui.imwrite(filename,image); } } 3.编写测试类: packagecom.njupt.zhb.test; publicclassTestMain{ publicstaticvoidmain(String[]args){ System.out.println("Hello,OpenCV"); //Loadthenativelibrary. System.loadLibrary("opencv_java246"); newDetectFaceDemo().run(); } } //运行结果: //Hello,OpenCV // //RunningDetectFaceDemo ///E:/eclipse_Jee/workspace/JavaOpenCV246/bin/com/njupt/zhb/test/lbpcascade_frontalface.xml //Detected8faces //WritingfaceDetection.png 运行结果:

资源下载

更多资源
腾讯云软件源

腾讯云软件源

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

Nacos

Nacos

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

Rocky Linux

Rocky Linux

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

Sublime Text

Sublime Text

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

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