JAVA中正确使用的单例模式常用写法(6种写法)

星期六, 2017-11-04 | Author: Lee | JAVA-and-J2EE | 没有评论 2,810 views

单例模式 老生常谈的一种模式,也是实际项目代码中比较常用的一种模式了.

文中做了6种方法,实际用的最多的也就 4.5两种,其实6是最完美的但是感觉别捏呢,不像个类,用的也并不多.

1.懒汉式,线程不安全

public class Singleton {
    private static Singleton instance;
    private Singleton (){}
    public static Singleton getInstance() {
     if (instance == null) {
         instance = new Singleton();
     }
     return instance;
    }
}

2.懒汉式,线程安全 (BUT.效率差)

public static synchronized Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
}

3.双重检验锁

public static Singleton getSingleton() {
    if (instance == null) {                         //Single Checked
        synchronized (Singleton.class) {
            if (instance == null) {                 //Double Checked
                instance = new Singleton();       //非原子操作
            }
        }
    }
    return instance ;
}

问题:new Singleton非原子操作
1.给 instance 分配内存
2.调用Singleton 的构造函数来初始化成员变量
3.将instance对象指向分配的内存空间(执行完这步 instance 就为非 null 了)

解决办法 JDK1.5以前的版本会有问题, JDK1.5后用volatile关键字(立即可见及禁止指令重排序优化)来修饰变量.通过DCL(double checked locking)实现同步

public class Singleton {
    private volatile static Singleton instance; //这里为 volatile
    private Singleton (){}
    public static Singleton getSingleton() {
        if (instance == null) {                         
            synchronized (Singleton.class) {
                if (instance == null) {       
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }  
}

上面三种的写法基本上在项目中没有什么实用价值,下面的三种才是比较常用的

› 继续阅读

Tags: ,

Nginx配置静态文件404问题解决

星期一, 2017-10-23 | Author: Lee | computer, linux | 没有评论 3,838 views

Nginx提供了另外一个静态路径配置 : alias

alias与root区别

官方root

Sets the root directory for requests. For example, with the following configuration
location /i/ {
    root /data/w3;
}
The /data/w3/i/top.gif file will be sent in response to the “/i/top.gif” request

官方alias

Defines a replacement for the specified location. For example, with the following configuration
location /i/ {
    alias /data/w3/images/;
}
on request of “/i/top.gif, the file /data/w3/images/top.gif will be sent.

当访问/i/top.gif时,

root是去/data/w3/i/top.gif请求文件,

alias是去/data/w3/images/top.gif请求

root响应的路径:配置的路径+完整访问路径(完整的location配置路径+静态文件)

alias响应的路径:配置路径+静态文件(去除location中配置的路径)

修改配置为

location /api/v1/upload {  
     alias /home/v1/upload/;  
}

注意

使用alias时目录名后面一定要加“/”

一般情况下,在location /中配置root,在location /other中配置alias

Tags:

支持emoji图标直接存储到数据库,更改MySQL数据库的编码为utf8mb4

星期一, 2017-10-23 | Author: Lee | Database, JAVA-and-J2EE | 一条评论 2,532 views

随着emoji的频繁使用,对接微信后会带名字的emoji的很多,现在都需要支持.

utf-8编码可能2个字节、3个字节、4个字节的字符,但是MySQL的utf8编码只支持3字节的数据,而移动端的表情数据是4个字节的字符。

如果直接往采用utf-8编码的数据库中插入表情数据,java程序中将报SQL异常:

1
2
3
4
5
6
7
8
9
java.sql.SQLException: Incorrect string value: ‘\xF0\x9F\x92\x94’ for column ‘name’ at row 1 
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073) 
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3593) 
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3525) 
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1986) 
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2140) 
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2620) 
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1662) 
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1581)

可以对4字节的字符进行编码存储,然后取出来的时候,再进行解码。但是这样做会使得任何使用该字符的地方都要进行编码与解码。

utf8mb4编码是utf8编码的超集,兼容utf8,并且能存储4字节的表情字符。

采用utf8mb4编码的好处是:存储与获取数据的时候,不用再考虑表情字符的编码与解码问题。

更改数据库的编码为utf8mb4:

1. MySQL的版本

utf8mb4的最低mysql版本支持版本为5.5.3+,若不是,请升级到较新版本。

2. MySQL驱动

5.1.34可用,最低不能低于5.1.13

3.修改MySQL配置文件
my.cnf一般在/etc/my.cnf位置。找到后请在以下三部分里添加如下内容:

1
2
3
4
5
6
7
8
9
10
[mysqld] 
character-set-client-handshake = FALSE 
character-set-server = utf8mb4 
collation-server = utf8mb4_unicode_ci 
init_connect='SET NAMES utf8mb4'
 
[client] 
default-character-set = utf8mb4 
[mysql] 
default-character-set = utf8mb4

4. 重启数据库,检查变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
SHOW VARIABLES WHERE Variable_name LIKE 'character_set_%' OR Variable_name LIKE 'collation%';
 
Variable_name	Value
character_set_client	utf8mb4
character_set_connection	utf8mb4
character_set_database	utf8mb4
character_set_filesystem	binary
character_set_results	utf8mb4
character_set_server	utf8mb4
character_set_system	utf8
collation_connection	utf8mb4_unicode_ci
collation_database	utf8mb4_unicode_ci
collation_server	utf8mb4_unicode_ci
collation_connection 、collation_database 、collation_server是什么没关系。
 
但必须保证
 
系统变量	描述
character_set_client	(客户端来源数据使用的字符集)
character_set_connection	(连接层字符集)
character_set_database	(当前选中数据库的默认字符集)
character_set_results	(查询结果字符集)
character_set_server	(默认的内部操作字符集)
这几个变量必须是utf8mb4。

5. 数据库连接的配置

数据库连接参数中:
characterEncoding=utf8会被自动识别为utf8mb4,也可以不加这个参数,会自动检测。
而autoReconnect=true是必须加上的。

6. 将数据库和已经建好的表也转换成utf8mb4

更改数据库编码:ALTER DATABASE xxdb CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

更改表编码:ALTER TABLE TABLE_NAME CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
如有必要,还可以更改列的编码

› 继续阅读

Tags: , ,

wordpress的自动登录及授权QQ等登录的处理

星期四, 2017-10-12 | Author: Lee | wordpress | 没有评论 1,929 views

以前处理了qq的自动登录,wordpress升级到4.8.2的版本,同时使用https,不知道什么原因就无法使用了.

需要新增 do_action( ‘wp_login’); 即可,以前版本只需要设置cookie 和current.

处理代码如下:

1
2
3
4
 require_once("../../../wp-config.php");
 wp_set_auth_cookie($wpuid);
 wp_set_current_user($wpuid);
 do_action('wp_login');

Tags:

启用新域名且同时迁移到https下

星期一, 2017-10-09 | Author: Lee | computer | 没有评论 1,907 views

https://www.pomelolee.com/ 新域名为 pomelo lee 的拼写(柚子李)

历史包袱多,要显示绿色的小锁(https),破费周折,改对应的 css中的图片引用等,数据库中的 文章的替换.

记忆下时间 2017-10-08 启用搭建,申请对应的CA证书(阿里云提供的免费一年的DV证书),到发稿才算真的完成.

Tags:

并发处理之幂等性(分布式锁机制)

星期五, 2017-08-18 | Author: Lee | JAVA-and-J2EE | 没有评论 6,835 views

什么是幂等性
幂等性就是指:一个幂等操作任其执行多次所产生的影响均与一次执行的影响相同。
用数学的概念表达是这样的: f(f(x)) = f(x).
就像 nx1 = n 一样, x1 就是一个幂等操作。无论是乘以多少次结果都一样。

常见的幂等性问题
幂等性问题经常会是由网络问题引起的,还有重复操作引起的。
› 继续阅读

Tags: ,

聊以纪念一起奋战的哥们

星期三, 2017-08-16 | Author: Lee | JAVA-and-J2EE | 没有评论 1,694 views

写下此行文字是很痛苦的,纪念一起奋战2年的哥们Leeyy同学,20170812,20170815悼.

golang开发的小工具的小问题总结

星期五, 2017-07-07 | Author: Lee | linux | 没有评论 2,689 views

用golang 开发了个自动抓取的小工具,同时受控服务器的任务分发.

小问题总结
1.build后的文件太大(5M)启用这种编译后(3M),更多加壳压缩太麻烦 没有弄了

解决采用:go build -ldflags “-s -w” 这种方式编译。

解释一下参数的意思:

-ldflags: 表示将后面的参数传给连接器(5/6/8l)
-s:去掉符号信息
-w:去掉DWARF调试信息
注意:

-s 去掉符号表(这样panic时,stack trace就没有任何文件名/行号信息了,这等价于普通C/C+=程序被strip的效果)

-w 去掉DWARF调试信息,得到的程序就不能用gdb调试了

2.工具启动后不允许崩溃 异常捕获 使用recover 捕获调用异常

package main
 
import (
    "fmt"
    "time"
)
 
func main() {
    i := 10000
    for j := 0; j < 3; j++ {
        // 使用多协程处理,其中可以预见的是除数为0会抛出异常
        go divide(i, j)
    }
 
    // 为了保证前面线程运行完,这里休眠一下
    for {
        time.Sleep(1 * time.Second)
    }
}
 
func divide(i, j int) {
    // 定义recover方法,在后面程序出现异常的时候就会捕获
    defer func() {
        if r := recover(); r != nil {
            // 这里可以对异常进行一些处理和捕获
            fmt.Println("Recovered:", r)
        }
    }()
 
    fmt.Println(i / j)
}

Tags:

let’s encrypt 遭遇升级错误的解决

星期四, 2017-06-08 | Author: Lee | JAVA-and-J2EE, linux | 没有评论 3,513 views

自动续期遭遇错误
使用的自动续期的指令是:

./letsencrypt-auto renew --email service@i5a6.com --agree-tos --force-renewal

错误如下:
Upgrading certbot-auto 0.13.0 to 0.14.2…
Replacing certbot-auto…
Creating virtual environment…
Installing Python packages…
Installation succeeded.
/root/.local/share/letsencrypt/lib/python2.6/site-packages/cryptography/__init__.py:26: DeprecationWarning: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of cryptography will drop support for Python 2.6
DeprecationWarning
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Failed to find executable apachectl in expanded PATH: /usr/bin:/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
Certbot doesn’t know how to automatically configure the web server on this system. However, it can still get a certificate for you. Please run “letsencrypt-auto certonly” to do so. You’ll need to manually configure your web server to use the resulting certificate.

问题分析及解决方法:
是升级到新的0.14的版本时候,有做自动重启apache 和nginx的配置,如果不指定讲默认按照 apache的配置

如果没有安装或者没有默认安装都是找不到的

解决之法 只需执行renew即可,不要再指定信息即可完成,然后再重新载入nginx即可 强制参数要带否则不会更新到远程刷新

./letsencrypt-auto renew -v --agree-tos --force-renewal

更多的信息可以使用指令查看

./letsencrypt-auto --help

Tags: ,

nginx启用https的注意和妥协支持http2及IE8以下版本http

星期四, 2017-06-01 | Author: Lee | JAVA-and-J2EE, linux | 没有评论 3,617 views

站点启用https的支持后,IE8等低版本有一系列的问题(加载http等警告等),妥协是在IE8以下版本重定向到http去,
本文是基于nginx做的处理,支持http2协议,环境centos6.9

一: nginx-1.12.0 指定编译 openssl-1.0.2l.tar.gz及支持http2(openssl起1.0.2版本才支持)

二.重新编译nginx

1.核查版本
#sbin/nginx -V #查看版本
2.下载
#wget http://nginx.org/download/nginx-1.12.0.tar.gz #下载
#tar xzvf nginx-1.12.0.tar.gz #解压缩
#cd nginx-1.12.0
 
3.编译
./configure --user=www --group=www --prefix=/usr/local/webserver/nginx --with-http_stub_status_module --with-openssl=/usr/local/webserver/openssl --with-http_ssl_module --with-pcre=/ia/data/tgz/pcre-8.32 --with-http_realip_module --with-http_image_filter_module --with-http_v2_module
 
#make
#mv /usr/local/webserver/nginx/sbin/nginx /usr/local/webserver/nginx/sbin/nginx.old #移动旧版本
#cp objs/nginx /usr/local/webserver/nginx/sbin/ #复制新版本nginx过去
 
4.启动新的,关掉旧的
让nginx把nginx.pid改成nginx.pid.oldbin 跟着启动新的nginx
# kill -USR2 `cat /usr/local/webserver/nginx/nginx.pid`
退出旧的nignx
# kill -QUIT `cat /usr/local/webserver/nginx/nginx.pid.oldbin
5.升级完成。
# sbin/nginx -V

三:(443端口)配置IE8以下版本重定向,(80端口)其他版本支持https

if ($http_user_agent !~* "MSIE [5-8].[0-9]") {
        rewrite (.*) https://www.iatodo.com$1 permanent;
        break;
    }
if ($http_user_agent ~* "MSIE [5-8].[0-9]") {
        rewrite (.*) http://www.iatodo.com$1 permanent;
        break;
    }

Tags: , ,

Search

文章分类

Links

Meta