‘编程学习’ 分类下的所有文章
2016八月19

Nginx:绑定域名代理tomcat

server {
	listen 80;
	listen 443 ssl;
	if ( $scheme = "http" ) {
            rewrite ^(.*) https://$host$1;
	}
	server_name nutzwk.wizzer.cn;
	root "/java/work/nutzwk";	
	ssl_certificate /java/work/1_nutzwk.wizzer.cn_bundle.crt;
	ssl_certificate_key /java/work/2_nutzwk.wizzer.cn.key;
	add_header "X-UA-Compatible" "IE=Edge, chrome=1";
	location / {
		proxy_pass http://127.0.0.1:9091;
		proxy_set_header Host $host;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	}
}
2016八月16

备份:HttpClient 4.x POST请求

            List<BasicNameValuePair> formParams = new ArrayList<>();
            formParams.add(new BasicNameValuePair("urlpp", ""));
            formParams.add(new BasicNameValuePair("urlkm", ""));
            formParams.add(new BasicNameValuePair("khjb", "2"));
            HttpEntity httpEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
            HttpPost httpPost = new HttpPost(tesseract.njwztx_baseUrl + "fetchNextList.action");
            httpPost.setEntity(httpEntity);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
            httpPost.setHeader("Cookie", "rememberPhone=1; phoneNumber=" + tesseract.getNjwztx_dhhm() + "; friendlyReminder=true;JSESSIONID=" + JSESSIONID + ";");
            HttpClient httpclient = HttpClients.createDefault();
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            Header[] headers = response.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                log.debug("header" + i + ":::" + headers[i]);
            }
            if (entity != null) {
                log.debug("getContentEncoding:::" + entity.getContentEncoding());
                log.debug("getContentType:::" + entity.getContentType());
                String str = EntityUtils.toString(response.getEntity());
                log.debug(str);
                Files.write("2.html", str);
            }
2016七月25

Maven:下载慢的解决办法

C:\Windows\System32\drivers\etc\hosts

151.101.24.215 repo.maven.apache.org

2016七月4

Nginx:配置静态资源304缓存

location ~ \.(jpg|png|jpeg|gif)$  {
        expires 30d;
        root   /data/www/wizzer.cn/;
}

location ~ \.(js|css)$  {
        expires 2h;
        root   /data/www/wizzer.cn/;
}
2016六月13

Docker:部署Node.js项目

 

Dockerfile:

FROM node:6.2
# Author
MAINTAINER wizzer "wizzer@qq.com"
ENV PORT 1337
RUN apt-get update && apt-get install -y \
		imagemagick \
	--no-install-recommends && rm -rf /var/lib/apt/lists/*
RUN mkdir -p /node/nodeshop
WORKDIR /node/nodeshop

RUN npm config set registry https://registry.npm.taobao.org
RUN npm i node-gyp -g
RUN npm i pm2 -g
ADD api /node/nodeshop/api
ADD assets /node/nodeshop/assets
ADD config /node/nodeshop/config
ADD tasks /node/nodeshop/tasks
ADD views /node/nodeshop/views
ADD app.js /node/nodeshop
ADD Gruntfile.js /node/nodeshop
ADD package.json /node/nodeshop
RUN npm i
EXPOSE ${PORT}
ENV LANG C.UTF-8
ENV TZ "Asia/Shanghai"
VOLUME ["/node/nodeshop/cert", "/node/nodeshop/upload", "/node/nodeshop/backup"]
CMD [ "pm2", "start", "--no-daemon", "app.js" ]

docker-compose.yml:

redis:
  image: redis
db:
  image: mariadb:5.5
  environment:
    "MYSQL_ROOT_PASSWORD": "xxxxxx"
    "MYSQL_DATABASE": "db123"
  command: "mysqld --character-set-server=utf8"
  ports:
    - "127.0.0.1:3306:3306"
  volumes:
    - "/node/nodeshop/db:/var/lib/mysql"
web:
  image: wizzer/nodeshop
  links:
    - redis
    - db
  environment:
    "MYSQL_HOST": "db"
    "MYSQL_USER": "root"
    "MYSQL_PASSWORD": "xxxxxx"
    "MYSQL_DATABASE": "db123"
    "MYSQL_LIMIT": 150
    "REDIS_HOST": "redis"
    "REDIS_PASS": ""
    "LOG_LEVEL": "verbose"
    "PORT": 1337
    "NODE_ENV": "development"
  command: "pm2 start /node/nodeshop/app.js --no-daemon"
  ports:
    - "1337:1337"
  volumes:
    - "/node/nodeshop/cert:/node/nodeshop/cert"
    - "/node/nodeshop/upload:/node/nodeshop/upload"
    - "/node/nodeshop/backup:/node/nodeshop/backup"

说明:
1、把数据库端口3306映射到127.0.0.1:3306 是为了还原数据库,web映射端口不绑定IP这样外网可以访问,通过nginx代理出去.
2、volumes将数据文件、数据库文件使用容器外文件夹,这样重启后不丢失数据.

1、打包最新image
docker build -t wizzer/nodeshop .

. 为当前文件夹,通过Dockerfile打包
wizzer/nodeshop:v1.0 用户名/项目:版本号

docker images 列出所有镜像
docker rmi ID 删除某个镜像
docker ps -a 列出所有容器
docker rm ID 删除某个容器
2、Centos安装Docker-engine 1.7.1版本(windows安装docker-toolbox即可)

vi /etc/yum.repos.d/docker.repo

[dockerrepo]
name=Docker Repository
baseurl=https://yum.dockerproject.org/repo/main/centos/6/
enabled=1
gpgcheck=1
gpgkey=https://yum.dockerproject.org/gpg

yum search docker
yum install docker-engine.x86_64
service docker start 启动docker服务
chkconfig docker on 设置为开启启动

3、Centos安装docker-compose 1.1.0版本(windows安装docker-toolbox即可)

curl -L https://github.com/docker/compose/releases/download/1.7.1/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose

ps:第一行命令复制会少符号,到 https://github.com/docker/compose/releases/ 复制命令。

4、迁移镜像
docker ps -a 列出容器快照
docker export ID > nodeshop.tar 将容器快照导出
cat /node/nodeshop.tar | docker import – wizzer/nodeshop 加载容器快照

5、创建运行目录
分别创建4个文件夹【必须】
/node/nodeshop/cert 将证书文件拷贝进去
/node/nodeshop/upload 附件上传文件夹
/node/nodeshop/backup 数据库备份文件夹
/node/nodeshop/db 数据库文件夹
将Dockfile 、 docker-compose.yml 拷贝到 /node/nodeshop 目录

6、启动项目

cd /node/nodeshop
docker-compose up -d

docker-compose ps 列出正在运行的服务
docker-compose stop 停止服务
docker ps -a 列出所有容器状态
docker rm ID 删除容器

若要修改环境变量,可以修改 /node/nodeshop/docker-compose.yml 文件内容

7、安装mariadb客户端(用于连接数据库)

cd /etc/yum.repos.d/
vi MariaDB.repo

[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/5.5/centos6-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

yum install MariaDB-client

MariaDB-server 不需要安装

8、还原数据

mysql -h 127.0.0.1 -u root -p
密码
show databases;
use nodeshop;
source /node/nodeshop/db.sql;
show tables;
exit;

9、重启docker容器

docker-compose stop
docker-compose start

10、进入容器执行命令,比如测试网络情况

docker ps -a
docler exec -it ID /bin/bash
ping 192.168.1.11
exit

如果网络不通,可能需要关闭防火墙,然后重启docker服务:

service docker restart

11、容器开机自启动

vi /etc/rc.d/rc.local
/usr/local/bin/docker-compose -f /node/sunshop/docker-compose.yml up -d

注意:如果是centos7 则需要执行 chmod +x /etc/rc.d/rc.local 添加执行权限.

 


本教程适用于Centos6.x版本,7或有不同。

2016五月24

Node.js:集成apidoc

本文基于Sails.js MVC框架
一、安装

npm i apidoc -save
npm i grunt-apidoc -save

二、配置

package.json

增加配置项

"apidoc": {
  "title": "Sunshop"
},

tasks/config/apidoc.js

/**
 * Created by wizzer on 2016/5/24.
 */
module.exports = function (grunt) {
  grunt.config.set('apidoc', {
    myapp: {
      src: "api/controllers/api",
      dest: "apidoc/",
      options: {
        includeFilters: [ ".*\\.json$" ]
      }
    }
  });
  grunt.loadNpmTasks('grunt-apidoc');
};

tasks/register/compileAssets.js

module.exports = function (grunt) {
	grunt.registerTask('compileAssets', [
		'clean:dev',
		'jst:dev',
		'less:dev',
		'copy:dev',
		'coffee:dev',
    'apidoc:myapp' // <-- apidoc
	]);
};

 

api/controllers/api/oauth.json  一个API文档示例,详细参数见apidoc官网。

/**
 * @api {POST} /api/oauth/token Token
 * @apiName Token
 * @apiGroup Oauth
 * @apiVersion 1.0.0
 * @apiDescription 获取Token
 * @apiPermission anyone
 *
 * @apiParam {string} client_id client_id
 * @apiParam {string} client_secret client_secret
 *
 * @apiParamExample {json} 示例
 *   POST /api/oauth/token
 *   {
 *      "client_id": "client_id",
 *      "client_secret": "client_secret"
 *   }
 *
 * @apiSuccess (成功) {number} code 0
 * @apiSuccess (成功) {string} msg success
 * @apiSuccess (成功) {Object} data Token对象
 * @apiSuccess (成功) {string} data.token Token
 * @apiSuccess (成功) {number} data.expires 失效时间(24小时)请保存若失效重新获取
 * @apiSuccess (成功) {number} data.appid AppId
 * @apiSuccessExample {json} 示例
 *   HTTP/1.1 200 OK
 *   {
 *     "code": 0,
 *     "msg": "success",
 *     "data": {
 *       "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOjIsImV4cCI6MTQ2NDE1NjA2OTg3Nn0.4i_o7gCjCKvOImSi4peCMgCUrzpdgbtmvMECKf5wkqE",
 *       "expires": 1464156069876,
 *       "appid": 2
 *     }
 *   }
 *
 * @apiError (失败) {number} code 1:client_id不存在 2:client_id禁用 3:client_secret错误 4:参数错误
 * @apiError (失败) {string} msg 错误文字描述
 * @apiErrorExample {json} 示例
 *   HTTP/1.1 200 OK
 *   {
 *     "code": 1
 *     "msg": "client_id has error"
 *   }
 */

框架配置静态目录,让其可访问:
config/http.js

customMiddleware: function (app) {
    app.use('/apidoc', require('express')['static'](require('path').normalize(__dirname + '/../apidoc')));
},
2016五月18

Node.js 企业级开发框架

基于Sails.js MVC框架,路由自动映射,完善的权限控制体系,优美的后台界面。

集成最基础的通用功能:

系统(机构管理、用户管理、角色管理、菜单管理、定时任务、数据库备份、IP访问控制、登录日志等)

CMS(站点管理、栏目管理、内容管理、广告及链接等)

微信(会员列表、微信消息、群发消息、自动回复、关键词回复、帐号配置、菜单配置等)

 

演示地址:http://www.nodeshop.cn

联系方式:QQ  1162-4317   (备注nodejs)

 

界面截图:

QQ截图20160518095645

2

2016五月4

Node.js:集成QQ信任登录

1、申请AppId、AppKey和验证字符串

http://connect.qq.com/manage/login

网站首页头文件添加验证字符串,如:

<meta property=”qc:adminscontent=”765754250763563070636” />

填写回调地址:

必须是公网地址,可以填写多个,注意 /xxx 和 http://wizzer.cn/xxx 是两个地址,两个都需要配置。

2、开发完成

登录页面:

<span id=”qqLoginBtn”></span>

<script type="text/javascript" src="http://qzonestyle.gtimg.cn/qzone/openapi/qc_loader.js" data-appid="<%=qq_appid||''%>" data-redirecturi="<%=req.baseUrl%>/public/shop/pc/account/oauthQq" charset="utf-8" ></script>
<script type="text/javascript">
  QC.Login({
    btnId:"qqLoginBtn",    //插入按钮的节点id
    scope: "get_user_info"
  },function(oInfo, oOpts){
    //登陆成功执行
    var nickname=QC.String.escHTML(oInfo.nickname);//获取QQ会员名
    var info={
      nickname:nickname,
      gender:oInfo.gender,
      headimgurl:oInfo.figureurl_qq_1 //头像40X40
    };//封装对象
    if(QC.Login.check()){
      QC.Login.getMe(function(openId, accessToken){
        info.openid=openId;//传递openid及昵称头像等,业务逻辑自动注册会员或登录
        $.post(
          "/public/shop/pc/account/oauthQqStatus",
          info,
          function(result){
            console.log(result);
            if(result.code==0){
              window.location.href=$("#r").val()||'/member';//登录成功跳转
            }else{
              alert('登录失败');
            }
          },'json'
        );
      });
    }
  });</script>

回调页面:

<script type="text/javascript" src="http://qzonestyle.gtimg.cn/qzone/openapi/qc_loader.js" charset="utf-8" data-callback="true"></script>

退出登录:

<%if(sails.config.system.ShopConfig.oauth_open&&sails.config.system.ShopConfig.pay_wxpay&&sails.config.system.ShopConfig.oauth_qq){
var qq_appid='';
  if(sails.config.system.ShopConfig.oauth_qq_info){
    qq_appid=sails.config.system.ShopConfig.oauth_qq_info.qq_appid;
}
%>
<script type="text/javascript" src="http://qzonestyle.gtimg.cn/qzone/openapi/qc_loader.js" data-appid="<%=qq_appid||''%>" data-redirecturi="http://<%=sails.config.system.AppDomain%>/public/shop/pc/account/oauthQq" charset="utf-8" ></script>
<script type="text/javascript">
  QC.Login.signOut();
  if(QC.Login.check()==false){
    window.location.href='/public/shop/pc/account/logout';//先QQ登出,再清除session
  }else{
    window.location.reload();
  }
</script>
<%}else{%>
<script type="text/javascript">
  window.location.href='/public/shop/pc/account/logout';
</script>
<%}%>

3、申请审核

审核条件:登录页面有QQ登录图标、使用申请的QQ或测试QQ号,测试可以正常登录后提交申请,否则肯定是不通过的。

 

2016三月2

Node.js 商城系统开发进展

商品规格、会员价、商品相册、图片缩放、二维码等等,用其他语言实现起来可能比较简单的功能,用node.js 实现起来,毕竟全靠自己摸索,花了好多时间,,好在做好了,泪奔。。

 

1 2 3 4

2015十二月20

Nginx+Tomcat负载均衡、绑定多域名、设置开机启动的安装步骤

1、JDK安装
/data1/soft/java/
>>chmod 777 jdk-6u45-linux-x64-rpm.bin
>>jdk-6u45-linux-x64-rpm.bin
>>gedit /etc/profile
JAVA_HOME=/data1/soft/java/jdk1.6.0_45

CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar

PATH=$JAVA_HOME/bin:$PATH
export JAVA_HOME
export CLASSPATH
export PATH
>>source /etc/profile

2、TOMCAT安装
将原windows系统中的tomcat主要文件拷贝到linux(conf、lib、bin),并新建空文件夹(logs、temp、work)
/data1/soft/tomcat1 多网站的那个tomcat
/data1/soft/tomcat2 少网站的那个tomcat
分别修改两个tomcat下的server.xml文件,将项目路径分别替换为 /data1/www/websties1 和 /data1/www/websties2
>>/data1/soft/tomcat/bin/startup.sh //启动tomcat
>>/data1/soft/tomcat/bin/shutdown.sh //停止tomcat

开机启动:
http://jingyan.baidu.com/article/6525d4b1382f0aac7d2e9421.html
【tomcat1、tomcat2分别设置为启动项】
除了百度经验之外,要在catalina.sh 里加上下面三行,否则在自启动的时候找不到jdk
export JAVA_HOME=/data1/soft/java/jdk1.6.0_45
export CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export PATH=$JAVA_HOME/bin:$PATH

3、Nginx安装
>>rpm -ivh http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm
>>yum -y install nginx
通过命令安装后
配置文件:/etc/nginx/nginx.conf
域名配置:/etc/nginx/conf.d/ 一个域名一个配置文件,不要的域名可以备份后删除

server {
listen 80;
server_name test.wizzer.cn;
location / {
proxy_pass http://test.wizzer.cn:8101;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

日志文件路径:/var/logs/nginx
服务启动或通知
>>service nginx stop
>>service nginx start
设置为随机启动
>>chkconfig nginx on

4、Nginx代理权限设置
若通过域名+端口号可访问,但80端口显示 502 Bad Gateway ,日志/var/logs/nginx/error.log报
2015/12/19 18:02:03 [crit] 9978#0: *8 connect() to 61.132.139.155:8101 failed (13: Permission denied) while connecting to upstream, client: 124.73.13.21, server: test.wizzer.cn, request: “GET / HTTP/1.1”, upstream: “http://61.132.139.155:8101/”, host: “test.wizzer.cn”
则需要设置selinux权限(宽容模式):
>>setenforce 0
>>setsebool -P httpd_can_network_connect 1

5、防火墙配置
>>vi /etc/sysconfig/iptables
#########################################################
# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state –state NEW -m tcp -p tcp –dport 21 -j ACCEPT
-A INPUT -m state –state NEW -m tcp -p tcp –dport 22 -j ACCEPT
-A INPUT -m state –state NEW -m tcp -p tcp –dport 80 -j ACCEPT
-A INPUT -j REJECT –reject-with icmp-host-prohibited
-A FORWARD -j REJECT –reject-with icmp-host-prohibited
COMMIT
#########################################################

>>/etc/init.d/iptables restart #重启防火墙使配置生效,或者命令 service iptables restart