fesh1124
在你想要放弃的那一刻,想想为什么当初坚持走到了这里...

导航

 

 

1、Hadoop错误:Name node is in safe mode

解决:关闭Hadoop安全模式  

hadoop dfsadmin -safemode leave

2、解压缩.gz 和 .bz2格式文件

在 tar 命令所在的那一行中,x 标记指定 tar 命令执行解压缩操作,f 标记则指定压缩包的文件名。 tar -xf spark-1.2.0-bin-hadoop2.4.tgz

.tar.gz     格式解压为          

tar   -zxvf   xx.tar.gz

.tar.bz2   格式解压为          

tar   -jxvf    xx.tar.bz2

3、从Windows到Linux文件乱码解决命令

iconv -f GBK -t UTF-8 aa.json -o bb.json

 4、解压.bin文件

./**.bin

在JDK官网下载了一个jdk-6u45-linux-x64.bin

解压命令为:

./jdk-6u45-linux-x64.bin

 5、MySQL中文乱码

编辑 /etc/mysql/my.cnf

[client]
default-character-set=utf8

[mysqld]
character-set-server=utf8

然后重启MySQL

sudo /etc/init.d/mysql restart
show variables like 'character%';

CentOS

 vi /etc/my.cnf

 

service mysqld restart

6、CentOS常用命令

关闭防火墙  chkconfig iptables off

查看防火墙状态  service iptables status 

 

http://blog.csdn.net/hooperzao/article/details/25111321

http://bdbaishitong.blog.163.com/blog/static/201493080201378662648/

CentOS 7关闭防火墙

systemctl stop firewalld.service #停止firewall

systemctl disable firewalld.service #禁止firewall开机启动

 7、Linux修改文件夹权限及拥有者

chmod -R 777 file

chown -R hadoop:hadoop file

8、Tomcat启动停止

以服务启动Tomcat         nohup bin/startup.sh &

关闭Tomcat服务           bin/shutdown.sh

 9、Java解析CST格式时间

SimpleDateFormat simple = new SimpleDateFormat(
                "EEE MMM dd HH:mm:ss 'CST' yyyy", Locale.US);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.format(simple.parse(“Mon Nov 19 14:06:58 CST 2012”.toString())

 10、打开hiveserver2, 以后台进程的方式启动

hive --service hiveserver2 &

 11、MongoDB解析GridFS中的ISODate

Date simple = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'CST' yyyy",Locale.US);
Date result=simple.parse(simple.format(new Date()));

12、MongoDB多条件查询

查询某个时间区间的数据

BasicDBList conditionList = new BasicDBList();
conditionList.add(new BasicDBObject("uploadDate", new BasicDBObject("$gte", lowTime)));// 查询条件-时间下界
conditionList.add(new BasicDBObject("uploadDate", new BasicDBObject("$lte", highTime)));// 查询条件-时间上界


DBObject queryCondition = new BasicDBObject("$and", conditionList);

GridFS gf = new GridFS(db);


DBCursor cursor = gf.getDB().getCollection("fs.files").find(queryCondition);//从表 fs.files 中查询出所有JPG文件

或者

List<GridFSDBFile> fileList = gf.find(queryCondition);

删除GridFS中数据

gf.remove(queryCondition);// 删除GridFS中图片数据

参考:http://blog.csdn.net/mcpang/article/details/8731065

 13、jar文件后台运行

如果在终端中执行java -jar xxx.jar&命令,当终端关闭时,xxx.jar也会同时结束运行,但是如果执行nohup java -jar xxx.jar&命令,则程序会在后台一直运行,值得注意的是,此时程序控制台输出会被转移到nohup.out文件中。

14、MongoDB修改连接数

MongoClient client=new MongoClient ("127.0.0.1",27017);
MongoOptions option = client.getMongoOptions();
client.setConnectionsPerHost(100);// 设置每个主机的连接数
client.setThreadsAllowedToBlockForConnectionMultiplier(50);// 设置线程队列数

http://api.mongodb.org/java/2.13/

 15、清空文件夹并重建

File file = new File(System.getProperty("user.dir") + "/dataToMatch");
if (!file.exists() && !file.isDirectory()) {// 不存在
     file.mkdir();
} else if (file.exists() && file.isDirectory()) {// 存在
     String basePath = file.getAbsolutePath();
     String[] fileStrs = file.list();
     File tp = null;
     for (String path : fileStrs) {
           tp = new File(basePath + "/" + path);
           tp.delete();
     }
     file.delete();
     file.mkdir();
} else {
      TimerJob.log.info("ERROR!");
}

 16、List、Map、DBObject定义时初始化值

List

            List<String> list = new ArrayList<String>() {
                {
                    add("string1");
                    add("string2");
                    // some other add() code......
                    add("stringN");
                }
            };

Map

            Map<String, String> map = new HashMap<String, String>() {
                {
                    put("key1", "value1");
                    put("key2", "111cn.Net");
                    // .... some other put() code
                    put("keyN", "valueN");
                }
            };

BasicDBObject

            DBObject object=    new BasicDBObject() {
                {
                    put("name", name;
                    put("id", id);
                }
            };

 17、MySQL修改root密码

mysql -u root
mysql> use mysql;
mysql> UPDATE user SET Password = PASSWORD('newpass') WHERE user = 'root';
mysql> FLUSH PRIVILEGES;

http://jingyan.baidu.com/article/0320e2c198ad5f1b87507bc8.html

 18、CentOS 6.5 SSH免密码登陆

(1)检查linux是否安装了SSH,命令为:

rpm -qa | grep ssh

安装SSH命令

yum install ssh   或者     yum install openssh-server   yum -y install openssh-clients

(2)检查ssh服务是否开启,命令为:

service sshd status

若已经开启则显示为: 

/etc/init.d/sshd: line 33: /etc/sysconfig/sshd: Permission denied
openssh-daemon (pid  1946) is running...

若没有开启,则开启ssh服务,命令为:

service sshd start   或者   /etc/init.d/sshd start

(3)检查ssh是否是自动启动状态,命令为:

chkconfig --list sshd

2~5为on则表示ssh会在系统启动时自动启动

 (4)生成公钥和私钥

ssh-keygen -t rsa     或者    ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa

接着

cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys   或者   cat ~/.ssh/id_dsa.pub >> ~/.ssh/authorized_keys

(5)在服务器上更改权限

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

(6)验证

ssh -version
ssh localhost

(7)查看是否启动22端口

netstat -antp | grep sshd

 19、Hadoop错误 org.apache.hadoop.yarn.exceptions.YarnException: Unauthorized request to start container.解决方法

问题原因:namenode,datanode时间同步问题

解决办法:多个datanode与namenode进行时间同步

在每台服务器上执行(把当前时区调整为上海+8区,然后利用ntpdate同步标准时间)

cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
ntpdate us.pool.ntp.org

如果没有ntpdate,则安装

yum install -y ntpdate

reboot重启之后,

查看时间和日期  

date

查看当前时区

date -R  

 20、CentOS7无法使用ifconfig

安装net-tools

yum install net-tools

 21、CentOS 6.5安装MySQL

1)安装

yum install -y mysql-server mysql mysql-devel

2)启动MySQL

service mysqld start

3)设置开机启动

chkconfig mysqld on

4)第一次启动MySQL后,设置root账号密码

mysqladmin -u root password '123456'

5) 设置远程登陆

登陆MySQL

mysql -u root -p

然后输入

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' identified by '123456'  WITH GRANT OPTION;

flush privileges;
exit

并重启MySQL

service mysqld restart

 22、hive错误解决

FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. MetaException(message:javax.jdo.JDODataStoreException: An exception was thrown while adding/validating class(es) : Specified key was too long; max key length is 767 bytes

解决办法:

登陆MySQL,运行

alter database hive character set latin1;

 23、Java写文件指定编码格式

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream("data\\" + date + ".txt"), "UTF-8"));

 24、JSP显示本地图片

需要设置虚拟目录,也就是说把硬盘上一个目录映射到tomcat的工作目录下,然后tomcat就可以根据一个映射关系找到硬盘中的文件了。

修改Tomcat的conf/server.xml文件

在<Host>标签内加入如下代码

<Context crossContext="true" docBase="/home/jason/upload" path="/upload" reloadable="true"></Context>

其中docBase就是本地电脑的绝对路径
path就是设置的虚拟路径
修改完之后需要重启tomcat服务器

然后,在JSP中调用

<input type="image" src="/upload/google.png" width="538px" height="190px" />

25、解压.rar文件

wget http://www.rarsoft.com/rar/rarlinux-4.0.1.tar.gz

 

tar -zxvf rarlinux-4.0.1.tar.gz
cd rar 
make

 运行命令rar时,出现下面这个问题

   rar: /lib/i686/nosegneg/libc.so.6: version `GLIBC_2.7' not found (required by rar)

则进入rar目录

cp rar_static /usr/local/bin/rar

解压rar文件

rar x file.rar 

打包成rar文件

rar file.rar ./file/

26、Java读写UTF-8文本

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("temp.txt")), "UTF-8"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("temp.txt")), "UTF-8"));

根据情况修改编码格式

unicode  unicode big endian
utf-8        utf-8
utf-16      unicode
gb2312  ANSI

27、查看操作系统版本相关信息

cat /etc/issue 

查看系统版本

cat  /etc/redhat-release

28、查看系统硬件信息

grep MemTotal /proc/meminfo   #查看内存总量
cat /proc/cpuinfo  #查看CPU信息

free -m 查看内存信息

29、查看端口状态

/etc/init.d/iptables status

参考:http://www.centoscn.com/CentOS/help/2013/0725/558.html

30、nameserver

vi /etc/resolv.conf

nameserver 8.8.8.8
nameserver 8.8.4.4
nameserver 127.0.0.1

 31、CentOS 6.5 修改系统ulimit 暨 org.apache.tomcat.jni.Error: 24: Too many open files 解决方法

vi /etc/security/limits.conf

添加

 

vi /etc/security/limits.d/90-nproc.conf

32、CentOS服务器 netstat命令 查看TCP连接数信息

netstat命令的功能是显示网络连接、路由表和网络接口的信息,可以让用户得知有哪些网络连接正在运作。在日常工作中,我们最常用的也就两个参数,即netstat –an,如下所示:

# netstat -an 

netstat  -an参数中stat(状态)的含义如下:

LISTEN:侦听来自远方的TCP端口的连接请求;
SYN-SENT:在发送连接请求后等待匹配的连接请求;
SYN-RECEIVED:在收到和发送一个连接请求后等待对方对连接请求的确认;
ESTABLISHED:代表一个打开的连接,我们常用此作为并发连接数;
FIN-WAIT-1:等待远程TCP连接中断请求,或先前的连接中断请求的确认;
FIN-WAIT-2:从远程TCP等待连接中断请求;
CLOSE-WAIT:等待从本地用户发来的连接中断请求;
CLOSING:等待远程TCP对连接中断的确认;
LAST-ACK:等待原来发向远程TCP的连接中断的确认;
TIME-WAIT:等待足够的时间以确保远程TCP连接收到中断请求的确认;
CLOSED:没有任何连接状态;

在日常工作中,我们可以用shell组合命令来查看服务器的TCP连接状态并汇总,命令如下:

netstat -an|awk '/^tcp/{++S[$NF]}END{for (a in S)print a,S[a]}' 

参数说明:
CLOSED:没有连接活动或正在进行的;
LISTEN:服务器正在等待的进入呼叫;
SYN_RECV:一个连接请求已经到达,等待确认;
SYN_SENT:应用已经开始,打开一个连接;
ESTABLISHED:正常数据传输状态,也可以近似的理解为当前服务器的并发数;
FIN_WAIT1:应用已经完成;
FIN_WAIT2:另一边同意释放;
ITMED_WAIT:等待所有分组死掉;
CLOSING:两边同时尝试关闭;
TIME_WAIT:另一边已初始化一个释放;
LAST_ACK:等待所有分组死掉;

统计 TCP连接数 命令:

netstat -an |grep 'ESTABLISHED' |grep 'tcp' |wc -l  

参考:http://blog.csdn.net/youngqj/article/details/763089

33、Windows下修改MySQL最大连接数

在C:\ProgramData\MySQL\MySQL Server 5.6目录下,修改my.ini

max_connections=3000

34、CentOS 6.5 x64安装htop

# yum install -y wget
# wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
# rpm -ivh epel-release-6-8.noarch.rpm
# yum repolist
# yum install -y htop

 35、MySQL去除字段中的空格

update `dictionary_0` set `abbre`=replace(`abbre`,' ','');

36、jQuery UI autocomplete的提示框属性设置

jquery-ui.css:

.ui-state-hover,
.ui-widget-content .ui-state-hover,
.ui-widget-header .ui-state-hover,
.ui-state-focus,
.ui-widget-content .ui-state-focus,
.ui-widget-header .ui-state-focus {
    border: 1px solid #DCDCDC;//设置鼠标经过提示条目时的边框颜色
    background: #DCDCDC url("images/ui-bg_glass_100_fdf5ce_1x400.png") 50% 50% repeat-x;//设置鼠标经过时提示条目的背景颜色
    font-weight: normal;//设置鼠标经过时字体的粗细
    color: #000000;//设置鼠标经过时字体的颜色
}
.ui-state-hover a,
.ui-state-hover a:hover,
.ui-state-hover a:link,
.ui-state-hover a:visited,
.ui-state-focus a,
.ui-state-focus a:hover,
.ui-state-focus a:link,
.ui-state-focus a:visited {
    color: #000000;
    text-decoration: none;
}

具体的可以尝试更改。

 

37、Cookie

在保存cookie之前把值编码下:

Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));

取cookie值时解码:

String value = URLDecoder.decode(cookie.getValue(), "UTF-8");

38、Hive启动报错(Hive 1.2.1+Hadoop 2.6.0)

 

Exception in thread "main" java.lang.IncompatibleClassChangeError: Found class jline.Terminal, but interface was expected
at jline.console.ConsoleReader.<init>(ConsoleReader.java:230)
at jline.console.ConsoleReader.<init>(ConsoleReader.java:221)

解决办法:

 

将/opt/hadoop-2.6.0/share/hadoop/yarn/lib 下的jline-0.9.94.jar换成hive lib中的jline-2.12.jar

39、-bash: jps: command not found

vi ~/.bash_profile

修改

PATH=$PATH:$HOME/bin     》》》     PATH=$PATH:$HOME/bin:/sbin:/usr/bin:/usr/sbin
source /etc/profile

40、Spark Streaming中空batches处理的两种方法

Spark Streaming是近实时(near real time)的小批处理系统。对给定的时间间隔(interval),Spark Streaming生成新的batch并对它进行一些处理。每个batch中的数据都代表一个RDD,但是如果一些batch中没有数据会发生什么事情呢?Spark Streaming将会产生EmptyRDD的RDD,它的定义如下:

package org.apache.spark.rdd

import scala.reflect.ClassTag
import org.apache.spark.{Partition, SparkContext, TaskContext}

/**
  * An RDD that has no partitions and no elements.
  */
private[spark] class EmptyRDD[T: ClassTag](sc: SparkContext) extends RDD[T](sc, Nil) {
  override def getPartitions: Array[Partition] = Array.empty

  override def compute(split: Partition, context: TaskContext): Iterator[T] = {
    throw new UnsupportedOperationException("empty RDD")
  }
}

  可以看到这个RDD并不对任何父RDD有依赖关系,我们不能调用compute方法计算每个分区的数据。EmptyRDD的存在是为了保证Spark Streaming中多个batch的处理是一致的。但是存在EmptyRDD有时候会产生一些问题,比如:如果你想将接收到的Streaming数据写入HDFS中:

    val ssc = new StreamingContext(args(0), "iteblog", Seconds(10))
    val socketStream = ssc.socketTextStream("www.iteblog.com", 8888)
    val outputDir = args(1)
    socketStream.foreachRDD(rdd => {
      rdd.saveAsTextFile(outputDir)
    })

 当你调用foreachRDD的时候如果当前rdd是EmptyRDD,这样会导致在HDFS上生成大量的空文件!这肯定不是我们想要的,我们只想在存在数据的时候才写HDFS,我们可以通过以下的两种方法来避免这种情况:

    socketStream.foreachRDD(rdd => {
      if (rdd.count() != 0) {
        rdd.saveAsTextFile(outputDir)
      }
    })

  EmptyRDD的count肯定是0,所以这样可以避免写空文件,或者我们也可以用下面方法解决:

    socketStream.foreachRDD(rdd => {
      if (!rdd.partitions.isEmpty) {
        rdd.saveAsTextFile(outputDir)
      }
    })

  EmptyRDD是没有分区的,所以调用partitions.isEmpty是true。这样也可以解决上述问题。

  虽然上面两种方法都可以解决这个问题,但是推荐使用第二种方法。因为第一种方法调用了RDD的count函数,这是一个Action,会触发一次Job的计算,当你的数据量比较大的时候,这可能会带来性能方面的一些影响;而partitions.isEmpty是不需要触发Job的。
  不过如果你使用的是Sprk 1.3.0,你可以调用isEmpty函数来判断一个RDD是否为空,这个函数是在SPARK-5270引入的。

转自:http://www.iteblog.com/archives/1304

41、YARN中的kill应用的操作命令

bin/yarn application -kill <applicationId>

42、Kafka基本操作

启动后台运行  /opt/kafka/bin/kafka-server-start.sh -daemon /opt/kafka/config/server.properties

停止 /opt/kafka/bin/kafka-server-stop.sh

命令行创建主题

/opt/kafka/bin/kafka-topics.sh --create --zookeeper 192.168.1.101:2181,192.168.1.102:2181,192.168.1.103:2181/kafka --replication-factor 1 --partitions 3 --topic Prediction

命令行创建生产者和消费者

/opt/kafka/bin/kafka-console-producer.sh --broker-list 192.168.1.101:9092,192.168.1.102:9092,192.168.1.103:9092 --topic Prediction
/opt/kafka/bin/kafka-console-consumer.sh --zookeeper 192.168.1.101:2181,192.168.1.102:2181,192.168.1.103:2181/kafka --topic Prediction

 43、CentOS查看文件大小

查找大文件

find pathName -type f -size +800M

查看某文件夹占用总的空间大小

du -h --max-depth=1 pathName

 44、Tomcat时区与系统时区不一致

修改catalina.bat 或 catalina.sh,添加

WINDOWS:

set JAVA_OPTS=%JAVA_OPTS% -Xms256m -Xmx800m -Duser.timezone=GMT+08

LINUX :

JAVA_OPTS="-Xms512m -Xmx900m -Duser.timezone=GMT+08"

 45、问题描述:VMware 12、CentOS7_1511,电脑死机,强制关机,重启后无法进行用户目录,挂载/home失败,出现如下bug

 

注:这里采用克隆一个虚拟系统来进行修复过程,以免修复错误造成损失。

修复过程:

1)输入root密码进入系统;

2)使用 df -h命令,可以看到没有挂载/home目录,而/etc/fstab中设置了默认挂载

3)使用 lvdisplay命令可以查看home所在的卷为/dev/centos/home

4)执行xfs_repair -n /dev/centos/home ,检查文件系统是否损坏

5)执行xfs_repair修复文件系统

# xfs_repair -L /dev/centos/home
Phase 1 - find and verify superblock...
Phase 2 - using internal log
        - zero log...
ALERT: The filesystem has valuable metadata changes in a log which is being
destroyed because the -L option was used.
        - scan filesystem freespace and inode maps...
agi unlinked bucket 4 is 2164932 in ag 1 (inode=1075906756)
agi unlinked bucket 7 is 2164935 in ag 1 (inode=1075906759)
agf_freeblks 56476472, counted 56476470 in ag 0
agi unlinked bucket 20 is 2011348 in ag 0 (inode=2011348)
agi unlinked bucket 28 is 1254556 in ag 0 (inode=1254556)
sb_ifree 502, counted 595
sb_fdblocks 228710581, counted 228715521
        - found root inode chunk
Phase 3 - for each AG...
        - scan and clear agi unlinked lists...
        - process known inodes and perform inode discovery...
        - agno = 0
data fork in ino 43450214 claims free block 6363218
data fork in ino 43450214 claims free block 6363219
imap claims a free inode 43450215 is in use, correcting imap and clearing inode
cleared inode 43450215
Metadata corruption detected at xfs_dir3_block block 0x14b71c8/0x1000
corrupt block 0 in directory inode 58326652
	will junk block
no . entry for directory 58326652
no .. entry for directory 58326652
problem with directory contents in inode 58326652
cleared inode 58326652
        - agno = 1
        - agno = 2
        - agno = 3
        - process newly discovered inodes...
Phase 4 - check for duplicate blocks...
        - setting up duplicate extent list...
        - check for inodes claiming duplicate blocks...
        - agno = 0
        - agno = 1
        - agno = 2
entry ".." at block 0 offset 32 in directory inode 58326656 references free inode 58326652
        - agno = 3
entry ".idea" in shortform directory 3328138473 references free inode 58326652
junking entry ".idea" in directory inode 3328138473
Phase 5 - rebuild AG headers and trees...
        - reset superblock...
Phase 6 - check inode connectivity...
        - resetting contents of realtime bitmap and summary inodes
        - traversing filesystem ...
entry ".." in directory inode 58326656 points to free inode 58326652
bad hash table for directory inode 58326656 (no data entry): rebuilding
rebuilding directory inode 58326656
        - traversal finished ...
        - moving disconnected inodes to lost+found ...
disconnected inode 1254556, moving to lost+found
disconnected inode 2011348, moving to lost+found
disconnected inode 43450214, moving to lost+found
disconnected inode 58326654, moving to lost+found
disconnected dir inode 58326656, moving to lost+found
disconnected inode 58326657, moving to lost+found
disconnected inode 101773608, moving to lost+found
disconnected inode 101827014, moving to lost+found
disconnected inode 101874234, moving to lost+found
disconnected inode 1075906756, moving to lost+found
disconnected inode 1075906759, moving to lost+found
disconnected inode 1075906772, moving to lost+found
disconnected dir inode 1141030705, moving to lost+found
disconnected dir inode 3328200787, moving to lost+found
Phase 7 - verify and correct link counts...
resetting inode 1254512 nlinks from 2 to 5
resetting inode 3328138473 nlinks from 5 to 4
done

6)重新挂载/dev/centos/home到/home

# mount -t xfs /dev/centos/home /home/

参考:http://www.mamicode.com/info-detail-669354.html

 46、分词

mmse4j

 public static String doAndFilter(String words) {
//        ParaConfiguration paraConfiguration = ParaConfiguration.getInstance();
//        String result = "";
//        if (null != words && !words.equals("")) {
//            Seg seg = new MaxWordSeg(dic);
//            MMSeg mmSeg = new MMSeg(new StringReader(words), seg);
//            try {
//                Word word;
//                while ((word = mmSeg.next()) != null) {
//                    // System.out.print(word + " ");
//                    if (word.getLength() > 1) {
//                        result += word + " ";
//                    }
//                }
//                // System.out.println();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        return result;
//    }

IKAnalyzer

 IKSegmenter ik = new IKSegmenter(new StringReader(words), false); //true粗粒度false细粒度
        Lexeme lex = null;
        try {
            while ((lex = ik.next()) != null) {
                System.out.print(lex.getLexemeText() + "|");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

 47、CentOS安装SBT

# curl https://bintray.com/sbt/rpm/rpm | sudo tee /etc/yum.repos.d/bintray-sbt-rpm.repo
# yum install sbt

48、ES 5.4.2启动报错

ERROR: [2] bootstrap checks failed
[1]: max file descriptors [4096] for elasticsearch process is too low, increase to at least [65536]
[2]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
[2017-06-22T14:43:25,884][INFO ][o.e.n.Node               ] [yTEiH2w] stopping ...
[2017-06-22T14:43:25,918][INFO ][o.e.n.Node               ] [yTEiH2w] stopped
[2017-06-22T14:43:25,919][INFO ][o.e.n.Node               ] [yTEiH2w] closing ...
[2017-06-22T14:43:25,932][INFO ][o.e.n.Node               ] [yTEiH2w] closed

解决问题1:

$ sudo vi /etc/security/limits.conf

 修改/etc/security/limits.conf文件,添加或修改:

*        hard    nofile           65536
*        soft    nofile           65536

或者

*    soft    nofile    65536
*    hard    nofile    131072
*    soft    nproc    2048
*    hard    nproc    4096

解决问题2:

$ sudo sysctl -w vm.max_map_count=262144

或者修改 /etc/sysctl.conf 文件,添加 “vm.max_map_count”设置

$ sysctl -a

参考 http://blog.csdn.net/kongxx/article/details/52993057

 49、安装RabbitMQ

1)安装erlang
yum install erlang
2)导入公共签名密钥
rpm --import https://www.rabbitmq.com/rabbitmq-release-signing-key.asc
3)下载rabbitmq安装包
wget http://www.rabbitmq.com/releases/rabbitmq-server/v3.6.10/rabbitmq-server-3.6.10-1.el7.noarch.rpm
4)安装rabbitmq
yum install rabbitmq-server-3.6.10-1.el7.noarch.rpm
5)启动
service rabbitmq-server start
/bin/systemctl start  rabbitmq-server.service

 50、EPEL源

# yum install -y epel-release.noarch
# yum repolist

# yum install -y epel-release.noarch

51、CURL

$ curl -i -X POST -H "Content-Type:application/json" -d "{  \"firstName\" : \"Frodo\",  \"lastName\" : \"Baggins\" }" http://localhost:8080/people
HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
Location: http://localhost:8080/people/53149b8e3004990b1af9f229
Content-Length: 0
Date: Mon, 03 Mar 2014 15:08:46 GMT
-i ensures you can see the response message including the headers. The URI of the newly created Person is shown
-X POST signals this a POST used to create a new entry
-H "Content-Type:application/json" sets the content type so the application knows the payload contains a JSON object
-d '{ "firstName" : "Frodo", "lastName" : "Baggins" }' is the data being sent

 52、CentOS 7安装sbt

curl https://bintray.com/sbt/rpm/rpm | sudo tee /etc/yum.repos.d/bintray-sbt-rpm.repo
sudo yum install sbt

 53、MongoDB Document 与JSON互转

# Document 转 对象
Document doc = new Document(); Employee emp = new Gson().fromJson(document.toJson(), Employee.class); # 对象 转 Document Customer customer = new Customer(); Document doc = Document.parse(new Gson().toJson(customer));

 

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.0</version>
</dependency>

 54、安装nodejs

Node.js 8

curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -
sudo yum -y install nodejs

参考:https://nodejs.org/en/download/package-manager/

 55、hadoop/spark切换端口

如果ssh端口不是操作系统默认的22端口,在这里假设ssh端口号为16922
在hadoop里面修改hadoop-env.sh,增加

export HADOOP_SSH_OPTS="-p 16922"

在spark里面修改spark-env.sh,增加

export SPARK_SSH_OPTS="-p 16922"

56、系统可用的处理器个数

Runtime.getRuntime().availableProcessors()

57、centOS7下安装GUI图形界面

1)在命令行下 输入下面的命令来安装Gnome包。

# yum groupinstall "GNOME Desktop" "Graphical Administration Tools"

2)更新系统的运行级别。

# ln -sf /lib/systemd/system/runlevel5.target /etc/systemd/system/default.target

3)重启机器。启动默认进入图形界面。

# reboot

 http://www.cnblogs.com/c-xiaohai/p/6509641.html

58、多线程 

ExecutorService executorService = Executors.newCachedThreadPool();

         AtomicInteger temp = new AtomicInteger();
            Dao.findAll().forEach(
                    score -> {
                        // Lambda Runnable
                        executorService.submit(() -> {
                            temp.incrementAndGet();
                            writeToMySQL(score.getId(), score.Id());
                            temp.decrementAndGet();
                        });
                    }
            );

while (true) {
            System.out.println(temp.get());
            if (temp.get() == 0) {
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("ExecutorService Stop ERROR");
                break;
            }
        }

 

59、CentOS安装sbt

curl https://bintray.com/sbt/rpm/rpm | sudo tee /etc/yum.repos.d/bintray-sbt-rpm.repo
sudo yum install sbt

  

60、SVN无法clean up

step1:到sqlite官网(http://www.sqlite.org/download.html)下载sqlite3.exe;找到PrecompiledBinariesforWindows,点击sqlite-shell-win32-x86-3080500.zip下载,300KB左右.
step2:将下载到的sqlite3.exe放到某文件目录(我这里是F:\devTools\sqlite3)
step3:然后设置svn源代码文件夹及文件显示所有文件(包括隐藏文件),会发现.svn/wc.db文件,将其复制到step2的目录下
step4:开始->运行->打开cmd命令,跳转到setp2的文件目录中,执行打开wc.db的操作,然后删除里面work_queue表的数据即可,具体见图:
step5:将wc.db覆盖到svn源代码目录的.svn目录下(替换原来的wc.db)。
step6:再次对svn目录进行clean操作,即可cleanUp成功。

http://blog.csdn.net/u012049463/article/details/41517343

 61、MongoDB 中文排序

默认情况下,中文字段会被当做一个普通的二机制字符串来对比。MongoDB 3.4支持指定collation使用中文排序。

https://docs.mongodb.com/manual/reference/collation/

http://www.mongoing.com/archives/3912

62、IDEA SBT

vi ~/.sbt/repositories

 

[repositories]

local

ui:http://uk.maven.org/maven2/
ui-ivy:http://uk.maven.org/maven2/,[organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext] 

typesafe:http://repo.typesafe.com/typesafe/releases/
typesafe-ivy: http://repo.typesafe.com/typesafe/ivy-releases/,[organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext], bootOnly
sbt-plugin: http://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/  
sonatype: http://oss.sonatype.org/content/repositories/snapshots  
repo2: http://repo2.maven.org/maven2/

 63、Spring data mongodb排序有三种方式

1)一个字段的排序 

query.with(new Sort(Direction.ASC,"onumber"));

2)多个字段时同时升序或者降序时

 query.with(new Sort(Direction.ASC,"a","b","c"));

3)不同的字段按照不同的排序

List<Sort.Order>orders=new ArrayList<Sort.Order>();
orders.add(newSort.Order(Direction.ASC, "a"));
orders.add(newSort.Order(Direction.DESC, "b"));
query.with(newSort(orders ));

 64、map排序

            // sort
            //将map.entrySet()转换成list
            List<Map.Entry<String, Double>> list = new ArrayList<>(Map.entrySet());
            //然后通过比较器来实现排序// With lambdas
            Collections.sort(list, (Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) -> {
                double temp = o2.getValue() - o1.getValue();
                if (temp > 0) {
                    return 1;
                } else if (temp == 0) {
                    return 0;
                } else {
                    return -1;
                }
            });

 65、查看CPU信息

cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c

查看内存信息

cat /proc/meminfo

 66、修改系统文件数限制、进程限制

*** [WARN] *** Your open file limit is currently 1024.  
 It should be set to 65000 to avoid operational disruption. 
 If you no longer wish to see this warning, set SOLR_ULIMIT_CHECKS to false in your profile or solr.in.sh
*** [WARN] ***  Your Max Processes Limit is currently 4096. 
 It should be set to 65000 to avoid operational disruption. 
 If you no longer wish to see this warning, set SOLR_ULIMIT_CHECKS to false in your profile or solr.in.sh
Warning: Available entropy is low. As a result, use of the UUIDField, SSL, or any other features that require
RNG might not work properly. To check for the amount of available entropy, use 'cat /proc/sys/kernel/random/entropy_avail'.

修改/etc/security/limits.conf文件,在最后添加

* hard nofile 65000
* soft nofile 65000
* hard nproc 65000
* soft nproc 65000

67、vim常用命令

i 切换到输入模式,以输入字符
ESC,退出输入模式,切换到命令模式
0 或功能键[Home]    这是数字『 0 』:移动到这一行的最前面字符处 
$ 或功能键[End]    移动到这一行的最后面字符处
G    移动到这个档案的最后一行

/word    向光标之下寻找一个名称为 word 的字符串。例如要在档案内搜寻 vbird 这个字符串,就输入 /vbird 即可! (常用)

x, X    在一行字当中,x 为向后删除一个字符 (相当于 [del] 按键), X 为向前删除一个字符(相当于 [backspace] 亦即是退格键) (常用)
dd    删除游标所在的那一整行(常用)
ndd    n 为数字。删除光标所在的向下 n 行,例如 20dd 则是删除 20 行 (常用)

yy    复制游标所在的那一行(常用)
nyy    n 为数字。复制光标所在的向下 n 行,例如 20yy 则是复制 20 行(常用)
p, P    p 为将已复制的数据在光标下一行贴上,P 则为贴在游标上一行! 举例来说,我目前光标在第 20 行,且已经复制了 10 行数据。则按下 p 后, 那 10 行数据会贴在原本的 20 行之后,亦即由 21 行开始贴。
但如果是按下 P 呢? 那么原本的第 20 行会被推到变成 30 行。 (常用) u 复原前一个动作。(常用) [Ctrl]+r 重做上一个动作。(常用)

 

i, I    进入输入模式(Insert mode):
i 为『从目前光标所在处输入』, I 为『在目前所在行的第一个非空格符处开始输入』。 (常用)
a, A    进入输入模式(Insert mode):
a 为『从目前光标所在的下一个字符处开始输入』, A 为『从光标所在行的最后一个字符处开始输入』。(常用)
o, O    进入输入模式(Insert mode):
这是英文字母 o 的大小写。o 为『在目前光标所在的下一行处输入新的一行』; O 为在目前光标所在处的上一行输入新的一行!(常用)
r, R    进入取代模式(Replace mode):
r 只会取代光标所在的那一个字符一次;R会一直取代光标所在的文字,直到按下 ESC 为止;(常用)

 68、Maven设置国内镜像地址

在maven的conf目录下的settings.xml文件的<mirrors>标签中增加以下内容

    <mirror>
        <id>alimaven</id>
        <mirrorOf>central</mirrorOf>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
    </mirror>

 69、设置阿里云maven仓库

<!-- 阿里云maven仓库 --> 
    <repositories>
        <repository>
            <id>public</id>
            <name>aliyun nexus</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>public</id>
            <name>aliyun nexus</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

 70、Tomcat设定时区 

JAVA_OPTS="-Xms512m -Xmx900m -Duser.timezone=GMT+08"

 71、年月日

    public void judgeTime() throws ParseException {
        SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetimeFormat.parse("2018-10-12 12:00:00"));
        calendar.setMinimalDaysInFirstWeek(7);
        //取得当前时间
        String currentTime = datetimeFormat.format(calendar.getTime());

        calendar.add(Calendar.DAY_OF_MONTH, -1);
        //前一天
        String beforeDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());

        int year = calendar.get(Calendar.YEAR);//
        int month = calendar.get(Calendar.MONTH) + 1;//0-11月
        int quarter = DateUtil.getQuarter(month);//季度
        int week = calendar.get(Calendar.WEEK_OF_YEAR);//
        String startTime, endTime, timeRange, pushDate;//开始时间/结束时间/时间范围/推送日期
        //-------------------------------- 日统计:每天凌晨1点,统计前一天(工作日)数据 ----------------------------------//
        // -------------------判断是否是工作日
        int workingDay = statisticsMapper.judgeWorkingDay(beforeDate);
        System.out.println("统计的日期:" + beforeDate + "\t" + (workingDay == 0 ? "工作日" : "非工作日"));
        if (workingDay == 0) {//工作日
            startTime = beforeDate + " 00:00:00";
            endTime = beforeDate + " 23:59:59";
            timeRange = year + "" + month + "" + calendar.get(Calendar.DAY_OF_MONTH) + "";
            pushDate = statisticsMapper.getNextWorkingDayAfterDate(beforeDate);  //日期的下一个工作日
            System.out.println("日统计:\t时间范围=" + timeRange
                    + "\t开始时间=" + startTime
                    + "\t结束时间=" + endTime
                    + "\t推送日期=" + pushDate
            );
        }
        //--------------------------------- 周统计:每周一凌晨1点,统计上一周数据 ----------------------------------//
        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(calendar.getTime());
            calendar1.add(Calendar.DAY_OF_MONTH, -6);
            startTime = datetimeFormat.format(calendar1.getTime());
            endTime = beforeDate + " 23:59:59";
            timeRange = year + "年第" + week + "周次";
            pushDate = statisticsMapper.getNextWorkingDayAfterDate(beforeDate);  //本周第一个工作日

            System.out.println("周统计:\t时间范围=" + timeRange
                    + "\t开始时间=" + startTime
                    + "\t结束时间=" + endTime
                    + "\t推送日期=" + pushDate
            );
        }
        //-------------------------------- 月度统计:每月度第一天凌晨1点,统计上一月度数据 ---------------------------------//
        if (currentTime.substring(8, 10).equals("01")) {//1日
            startTime = DateUtil.getStartTimeOfMonth(month);
            endTime = DateUtil.getEndTimeOfMonth(month);
            timeRange = year + "年第" + month + "月度";
            pushDate = statisticsMapper.getFirstWorkingDayOfMonth(currentTime.substring(0, 7));//本月第一个工作日
            System.out.println("月度统计:\t时间范围=" + timeRange
                    + "\t开始时间=" + startTime
                    + "\t结束时间=" + endTime
                    + "\t推送日期=" + pushDate
            );
            //------------------------------- 季度统计:每季度第一天凌晨1点,统计上一个季度数据 --------------------------------//
            if (currentTime.substring(5, 7).equals("01")
                    || currentTime.substring(5, 7).equals("04")
                    || currentTime.substring(5, 7).equals("07")
                    || currentTime.substring(5, 7).equals("10")) {//1月1日,4月1日,7月1日,10月1日
                startTime = DateUtil.getStartTimeOfQuarter(quarter);
                endTime = DateUtil.getEndTimeOfQuarter(quarter);
                timeRange = year + "年第" + quarter + "季度";

                System.out.println("季度统计:\t时间范围=" + timeRange
                        + "\t开始时间=" + startTime
                        + "\t结束时间=" + endTime
                        + "\t推送日期=" + pushDate
                );
                //-------------------------------- 年度统计:每年度第一天凌晨1点,统计上一年度数据 ---------------------------------//
                if (currentTime.substring(5, 7).equals("01")) {//1月1日
                    startTime = DateUtil.getStartTimeOfYear(year);
                    endTime = DateUtil.getEndTimeOfYear(year);
                    timeRange = year + "年度";

                    System.out.println("年度统计:\t时间范围=" + timeRange
                            + "\t开始时间=" + startTime
                            + "\t结束时间=" + endTime
                            + "\t推送日期=" + pushDate
                    );
                }
            }
        }
    }

 72、Restful API防止重复提交

后端根据请求的uriPath+userId+MD5(JsonString(所有参数))作为key,来确定唯一。采用redis分布式锁

采用计数器:每次request进来则新建一个以orderId为key的计数器,然后+1。

如果>1(不能获得锁): 说明有操作在进行,删除。
如果=1(获得锁): 可以操作。

操作结束(删除锁):删除这个计数器。

 73、warning: LF will be replaced by CRLF in src/xx.java.

提交检出均不转换

git config core.autocrlf false

 74、Spring boot应用指定profile

1)application.properties
#使用的环境名称
spring.profiles.active=dev

2)application.yml

#需要使用的配置文件
spring:
profiles:
active: prod

3)Program arguments
在IDE的Program arguments中配置参数
--spring.profiles.active=dev

4)虚拟机的方式
  在VM options下使用命令:-Dspring.profiles.active=prod
-Dspring.profiles.active=prod

5)命令行
  将项目打包成jar包,切换到命令行的界面下使用命令: java -jar application.jar --spring.profiles.active=prod进行打包。
java -jar application.jar --spring.profiles.active=prod

 75、

Mysql服务器的三种时区设置
1)系统时区 - 保存在系统变量system_time_zone
2)服务器时区 - 保存在全局系统变量global.time_zone
3)每个客户端连接的时区 - 保存在会话变量session.time_zone

 

MySQL查看时区

show global variables like'%time_zone%';

flush privileges;

 76、查看域名的HTTPS到期时间

# echo | openssl s_client -servername www.XX.cn -connect www.XX.cn:443 2>/dev/null | openssl x509 -noout -dates

 77、文件替换弹框

rz -y

 78、查看Nginx安装了哪些模块

nginx -V

查看Nginx版本信息

nginx -v

 重新载入配置文件

nginx -s reload

重启 Nginx

nginx -s reopen

停止 Nginx

nginx -s stop

 79、MySQL导出函数

mysqldump -hlocalhost -uroot -ntd -R hqgr > hqgr.sql
  其中的 -ntd 是表示导出存储过程;-R是表示导出函数

 80、tomcat调用接口报错

java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986

解决办法:

在Tomcat的catalina.properties文件中添加

tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}

 81、List转成Set

new HashSet<>(appIdList)

Set转成以逗号分隔的String

Set<String> set;
String.join(",", set);

以逗号分隔的String转成Set

Set<String> set;
set.addAll(Arrays.asList(strAppId.trim().split(",")))

 82、关闭Swagger

 在Swagger2Config上使用@Profile注解标识,@Profile({"dev","test"})表示在dev和test环境才能访问swagger-ui.html,prod环境下访问不了

 83、

 

 

 

 

 

 

 

 

 

 

 

posted on 2014-10-12 22:28  feshy  阅读(1672)  评论(0编辑  收藏  举报