Spring Boot加载Properties文件的方法

最近使用Spring Boot框架写了一个小网站.感觉Spring Boot写网站十分的优雅

本文将介绍如何在Spring Boot内引用Properties的值

1.开启文件扫描

2.在需要引入配置文件的Class上使用@PropertySource注解.

3.在Class中的属性上使用@Value注解来注入配置文件中的值.

 

演示

package org.jzbk.example.util;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Getter
@Component
@PropertySource(value = "classpath:versionInfo.properties")
public class VersionInfo {
    @Value("${example.platform}")
    private String platform;

    @Value("${example.version}")
    private String version;

    @Value("${example.branch}")
    private String branch;

    @Value("${example.buildDate}")
    private String buildDate;
}

 

Munin提示min must be less than max in DS definition

因为家中使用的树莓派意外损坏,使用NAS上的虚拟机来代替原来树莓派的工作.在配置Munin的时候出现错误,当更新网络设备数据时,munin服务器端报错

2016/12/20 17:30:05 [INFO] creating rrd-file for if_ens3->down: '/var/lib/munin/ARCHLINUX/mx.ARCHLINUX-if_ens3-down-d.rrd'
2016/12/20 17:30:05 [ERROR] Unable to create '/var/lib/munin/ARCHLINUX/mx.ARCHLINUX-if_ens3-down-d.rrd': min must be less than max in DS definition
2016/12/20 17:30:05 [ERROR] In RRD: Error updating /var/lib/munin/ARCHLINUX/mx.ARCHLINUX-if_ens3-down-d.rrd: opening '/var/lib/munin/ARCHLINUX/mx.ARCHLINUX-if_ens3-down-d.rrd': No such file or directory
2016/12/20 17:30:05 [INFO] creating rrd-file for if_ens3->up: '/var/lib/munin/ARCHLINUX/mx.ARCHLINUX-if_ens3-up-d.rrd'
2016/12/20 17:30:05 [ERROR] Unable to create '/var/lib/munin/ARCHLINUX/mx.ARCHLINUX-if_ens3-up-d.rrd': min must be less than max in DS definition
2016/12/20 17:30:05 [ERROR] In RRD: Error updating /var/lib/munin/ARCHLINUX/mx.ARCHLINUX-if_ens3-up-d.rrd: opening '/var/lib/munin/ARCHLINUX/mx.ARCHLINUX-if_ens3-up-d.rrd': No such file or directory

 

在做了一些搜索之后发现文章 https://github.com/mail-in-a-box/mailinabox/issues/896

 

执行munin-run if_ens3 config 后出现以下输出

graph_order down up
graph_title ens3 traffic
graph_args --base 1000
graph_vlabel bits in (-) / out (+) per ${graph_period}
graph_category network
graph_info This graph shows the traffic of the ens3 network interface. Please note that the traffic is shown in bits per second, not bytes. IMPORTANT: On 32-bitsystems the data source for this plugin uses 32-bit counters, which makes the plugin unreliable and unsuitable for most 100-Mb/s (or faster) interfaces, where traffic is expected to exceed 50 Mb/s over a 5 minute period.  This means that this plugin is unsuitable for most 32-bit production environments. To avoid this problem, use the ip_ plugin instead.  There should be no problems on 64-bit systems running 64-bit kernels.
down.label received
down.type DERIVE
down.graph no
down.cdef down,8,*
down.min 0
up.label bps
up.type DERIVE
up.negative down
up.cdef up,8,*
up.min 0
up.max -1000000
up.info Traffic of the ens3 interface. Maximum speed is -1 Mb/s.
down.max -1000000

根据文章的内容,应用munin-monitoring/munin@f982751到插件中即可修复这个问题.

 

使用以下patch可以解决问题

--- if_.orig    2016-08-02 23:52:05.691224811 +0200
+++ if_ 2016-08-02 23:52:49.563223127 +0200
@@ -91,7 +91,7 @@
     # iwlist first)
     if [[ -r /sys/class/net/$INTERFACE/speed ]]; then
             SPEED=$(cat /sys/class/net/$INTERFACE/speed 2>/dev/null)
-            if [[ -n "$SPEED" ]]; then
+            if [ -n "$SPEED" -a "$SPEED" -gt "0" ]; then
                 echo $SPEED
                 return
             fi

 

Spring Session整合Redisson

前言:

Redisson是一个在Redis的基础上实现的Java驻内存数据网格(In-Memory Data Grid)。它不仅提供了一系列的分布式的Java常用对象,还提供了许多分布式服务。其中包括(BitSet, Set, Multimap, SortedSet, Map, List, Queue, BlockingQueue, Deque, BlockingDeque, Semaphore, Lock, AtomicLong, CountDownLatch, Publish / Subscribe, Bloom filter, Remote service, Spring cache, Executor service, Live Object service, Scheduler service) Redisson提供了使用Redis的最简单和最便捷的方法。Redisson的宗旨是促进使用者对Redis的关注分离(Separation of Concern),从而让使用者能够将精力更集中地放在处理业务逻辑上。 (摘自官方WIKI)

 

Redisson在3.2.0版本里新增了对Spring-Session整合的支持.本文将介绍整合Spring-Boot Spring-Session Redisson的方法

1. 添加依赖

Maven

<dependency>
   <groupId>org.springframework.session</groupId>
   <artifactId>spring-session</artifactId>
   <version>1.2.2.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.redisson</groupId>
   <artifactId>redisson</artifactId>
   <version>3.2.0</version>
</dependency>

 

Gradle

compile 'org.springframework.session:spring-session:1.2.2.RELEASE'  
compile group: 'org.redisson', name: 'redisson', version:'3.2.0'

 

2.创建配置文件RedisConfig.java

package org.jzbk.example.configuration;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.spring.session.config.EnableRedissonHttpSession;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;

@EnableRedissonHttpSession
public class RedisConfig {
    @Bean(destroyMethod = "shutdown")
    public RedissonClient getRedis() throws IOException {
        return Redisson.create(
                Config.fromYAML(
                        new ClassPathResource("redisson.yaml").getInputStream()
                )
        );
    }
}

因为我的redisson.yaml在classpath根目录下,所以直接使用ClassPathResource,请根据实际情况来修改.

 

3.修改application.properties,增加下列配置

spring.session.store-type=redis
server.session.timeout=7200

 

4.启动项目,刷新页面即可看到成功整合成功.

 

参考: https://github.com/redisson/redisson/wiki/14.-Integration%20with%20frameworks#145-spring-session

Spring Boot使用@Cacheable注解

通常,我使用Hibernate的@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)注解来缓存@Entity类.

在JAP2规范内另一个注解@Cacheable有与Hibernate的@Cache的一样的功能使用@Cacheable的条件如下.

1.Entity Class实现Serializable接口

2.在Entity Class前加入@Cacheable(true)

例如

@Entity
@Cacheable(true) 
public class UserEntity implements Serializable {
 // properties
}

 

3.在配置文件内开启缓存[1]

spring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE

 

参考: http://docs.oracle.com/javaee/6/tutorial/doc/gkjio.html [1]

http://stackoverflow.com/questions/31585698/spring-boot-jpa2-hibernate-enable-second-level-cache

使用Nginx来让Varnish支持HTTP/2

越来越多的公司开始使用HTTP/2来提高他们网站的性能以及用户体验. 开启HTTP/2的方法很简单,但是如何开启在HTTP/2与SSL 当你使用Varnish? 正如我们所了解的,Varnish 4.*不支持SSL, 我们需要找到一个方法来让这些组件协同工作.

HTTP/2

正如你所设想的, 互联网进步我们终于有了新版本的HTTP协议, 它主要的有点是:

-流与复用: 一个HTTP/2连接可以包含多个同时打开的流。请求的多路是由具有用它自己的流相关联的每个HTTP请求/响应交换实现的。流基本上是相互独立的,因此阻塞或失速请求或响应不会阻止上其他流的进展。

-报头压缩: 在HTTP / 1.1中,报头字段不被压缩,他们会不必要地占用带宽和增加延迟。在HTTP /2中,引入了一个新的压缩机制(HPACK)。它消除了冗余的报头字段,限制漏洞已知安全攻击,并具有在有限的环境使用有限的内存要求。

-服务器端推送: HTTP /2允许服务器先发制人发送(或“推”)的响应到客户端相关联地以前客户端发起的请求。当服务器知道客户端将需要具有以充分处理对原始请求的响应可用的那些响应这可能是有用的。

很多现代的浏览器已经支持HTTP/2, 在采取一些简单的操作开启HTTP/2之后,你将会收到预期的收益.

你也许可能能够在官方的文档中获取一些更多的点子:
– Hypertext Transfer Protocol Version 2 (HTTP/2) – RFC 7540

– HPACK: Header Compression for HTTP/2 – RFC 7541

为什么你需要HTTP/2

以上所有的解释都是很好的,但是有一些人喜欢直接看到结果或者直接去感受,直到那时候他们才会受到启发. 我所找到的一个最好的,令人印象深刻的DEMO由Akamai创建. 在Akamai的DEMO中,对比了加载一张相同的图片使用HTTP/1/1和HTTP/2. 如果你的浏览器支持HTTP/2, 我建议你自己体验一下Akamai的DEMO. 此外,为了应对HTTP /2,你必须启用SSL,它会提高你的网站的安全性。

Varnish的经典方案

 

一般Varnish作为前端使用,在用户与Web Server之间,架构看起来像这样:

architecture-basic

当我们有个客户请求了一个页面, 他的请求落到Varnish上(因为Varnish监听80端口), 然后Varnish检查这个对象是否已缓存,然后直接返回给客户不需要请求后端服务器或者请求后端服务器生成这个URL的页面.

现在的问题是 Varnish 4.*不支持浏览器所要求的 HTTP/2 SSL. 我们不能直接要求Varnish来监听443端口然后更改一些配置参数.

Nginx的解决方案

一个可能的方案就是在Varnish前增加Nginx. 它将会负责HTTP/2的请求, SSL以及发送请求到Varnish通过HTTP/1.1. 我们新的架构图将会看起来像这个样子:

architecture-ssl-http2

安装Nginx

最低版本要求为1.9.5(只有从这个版本开始ngx_http_v2_module 模块可用). 我是用的系统是Centos7, 因为Chrome最近移除了对SPDY的支持, 新的H2需要OpenSSL 1.0.2h才支持. Centos 7.x 源内自带的OpenSSL版本比较低并且Nginx不支持HTTP/2(包括Nginx的更新源). 想要使Nginx支持HTTP/2 我们使用以下脚本来编译自己的.src.rpm来增加HTTP/2的支持.

#!/bin/bash
yum -y groupinstall 'Development Tools'
yum -y install wget openssl-devel libxml2-devel libxslt-devel gd-devel perl-ExtUtils-Embed GeoIP-devel

OPENSSL="openssl-1.0.2h"
NGINX="nginx-1.11.3-1"

mkdir -p /opt/lib
wget https://www.openssl.org/source/$OPENSSL.tar.gz -O /opt/lib/$OPENSSL.tar.gz
tar -zxvf /opt/lib/$OPENSSL.tar.gz -C /opt/lib

rpm -ivh http://nginx.org/packages/mainline/centos/7/SRPMS/$NGINX.el7.ngx.src.rpm
sed -i "s|--with-http_ssl_module|--with-http_ssl_module --with-openssl=/opt/lib/$OPENSSL|g" /root/rpmbuild/SPECS/nginx.spec
rpmbuild -ba /root/rpmbuild/SPECS/nginx.spec
rpm -ivh /root/rpmbuild/RPMS/x86_64/$NGINX.el7.centos.ngx.x86_64.rpm

 

SSL证书

另一个我们需要的就是SSL证书, 我们可以使用Let’s Encrpty的免费证书,不过在这里出于演示的目的,我们使用OpenSSL来创建一个证书

openssl req -newkey rsa:2048 -sha256 -keyout jzbk.key -nodes -x509 -days 365 -out jzbk.crt

另一个重要的事情,在创建证书的时候,请输入你的域名当 Common Name 出现的时候. 如果你使用这个证书,你的浏览器将会提示这个证书不可信,出于测试的目的,请忽略这个提示.

配置 Nginx (HTTP/2, SSL)

好了,现在我们将证书文件复制到/etc/nginx下,然后开始配置Nginx

server {
    # 443 - default port for SSL
    listen 443 ssl http2;
    server_name <SERVER NAME>;
    # Specify the certificate files
    ssl_certificate jzbk.crt;
    ssl_certificate_key jzbk.kry;
 
    location / {
        # Set recommended by Nginx version
        proxy_http_version 1.1;
 
        proxy_pass http://127.0.0.1:80;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-Port 443;
        proxy_set_header Host $host;
    }
}

设置Varnish

一个最简单的VCL如下

vcl 4.0;
 
backend local {
    .host = "127.0.0.1";
    .port = "8080";
}

之后请修改使你的Varnish监听80端口.

配置Web Server

WebServer我会选择Nginx, 我们已经设置了Varnish的后端服务器, 下面是一个最简单的Nginx配置Demo

server {
    # Listen the port configured in the Varnish *.vcl file.
    listen 8080;
 
    server_name <THE SAME SERVER NAME>;
    
    # Define trusted addresses that are known to send correct replacement addresses.
    set_real_ip_from   127.0.0.1;
    real_ip_header     X-Forwarded-For;
    real_ip_recursive on;
 
    #...
}

使用 Chrome 来测试

想要测试所有组件都正常工作,你可以安装一个Chrome的插件叫做 HTTP/2 and SPDY indicator

总结

使用Nginx或者Varnish来缓存并不重要, 但是你必须需要配置HTTP/2, 因为它是一个可以轻易实现的目标.

 

原文链接(有少许修改): https://victor.4devs.io/en/architecture/varnish-cache-http2-with-nginx.html

WordPress Multi User(WPMU) 404页面跳转BUG修复

在不接受注册的WordPress Multi User(WPMU)中在wp-config.php设置NOBLOGREDIRECT开启访问不存在的BLOG地址的时候进行跳转.

#跳转到主BLOG
define( 'NOBLOGREDIRECT', '%siteurl%' );

#跳转到指定URL
define( 'NOBLOGREDIRECT', 'http://www.example.com' );

 

当开启NOBLOGREDIRECT之后WPMU会出现所有站点的BLOG的404页面条船出错(跳转到NOBLOGREDIRECT置顶的地址)

根据官方给出的文档,修复的方法是,在WPMU的wp-content目录下创建mu-plugins文件夹[Muse Use Plugins(强制使用的插件)]

在mu-plugins内创建一个custom.php文件,内容如下

<?php
remove_action( 'template_redirect', 'maybe_redirect_404' );

强制WPMU加载这一段代码,刷新页面之后WPMU即可正常显示404页面.

Varnish4 按照域名选择后端服务器

在varnish使用中会涉及代理多个后端域名(或网站)的情况,可通过判断请求的URL来设置对应backend即可解决问题。
以varnish官方文档中例子说明(https://www.varnish-cache.org/docs/trunk/reference/vcl.html#examples):

#后端服务器www
backend www {
     .host = "www.example.com";
     .port = "80";
}

#后端服务器images
backend images {
     .host = "images.example.com";
     .port = "80";
}

sub vcl_recv {
     #如果host为www.example.com,设置后端服务器为www,(?i)表示匹配模式为不区分大小写
     if (req.http.host ~ "(?i)^(www.)?example.com$") {
          set req.http.host = "www.example.com";
          set req.backend = www;
     #如果为images.example.com,设置后端服务器为images
     } elsif (req.http.host ~ "(?i)^images.example.com$") {
          set req.backend = images;
     } else {
          error 404 "Unknown virtual host";
     }
}

另外在vcl_hash函数中一定要加上

hash_data(req.http.host);

Nginx让带www的域名跳转到根域名上和让不带www的根域名跳转到带www的域名上

在Nginx下有许多让带www域名跳转到不带www的根域名上或者让不带www跳转到www的域名上的方法

下面说一下我正在用的方法,希望对各位能有所帮助.

 

重定向非www域名到www上

单域名

server {
        server_name example.com;
        return 301 $scheme://www.example.com$request_uri;
}

全部域名

server {
        server_name "~^(?!www\.).*" ;
        return 301 $scheme://www.$host$request_uri;
}

 

重定向www域名到根域名上

单域名

server {
        server_name www.example.com;
        return 301 $scheme://example.com$request_uri;
}

全部域名

server {
         server_name "~^www\.(.*)$" ;
         return 301 $scheme://$1$request_uri ;
}

 

我们创建单独的 Server{} 块是Nginx官方推荐的最佳方法来实现跳转.

虽然WordPress下也有插件能在PHP级别上做到跳转,但是出于性能考虑,总是让Nginx来做Nginx可以做到的事.

使用Munin来监控Nginx

前言:

Munin是一款很高效的监控工具,拥有大量的插件. 对于Nginx来言,监控需要一点点的设置. 这一篇小轿车的目的就是手把手的来教你使用Munin来监控nginx请求数和状态.

本文中所有的操作都在Centos 7.1下完成, 理论上其他的发行版本也可以套用(或许需要一点点的修改)

 

正文:

首先,确定你的Nginx有http_stub_status_module模块. 执行nginx -V

[root@jp02 ~]# nginx -V
nginx version: nginx/1.11.3
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-4) (GCC)
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabledconfigure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules 
 --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.pid --lock-path=/var/run/nginx.lock 
 --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp 
 --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp 
 --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-http_ssl_module 
 --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module
 --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module 
 --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module 
 --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic 
 --with-http_perl_module=dynamic --add-dynamic-module=njs-0.1.0/nginx --with-threads --with-stream --with-stream_ssl_module 
 --with-stream_geoip_module=dynamic --with-http_slice_module --with-mail --with-mail_ssl_module --with-file-aio --with-ipv6 
 --with-http_v2_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong 
 --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic'

 

如果你在输出中没有找到–with-http_stub_status_module那你或许需要重新编译你的Nginx,或者安装Epel源中的版本

 

现在,增加nginx status到默认的虚拟主机内

location /nginx_status {
    stub_status on;    # activate stub_status module
    access_log off;    
    allow 127.0.0.1;   # restrict access to local only
    deny all;
}

 

当你完成之后,重新加载你的Nginx配置文件

sudo systemctl reload nginx

 

现在我们来配置Munin-node

使用任意一个你喜欢的文件编辑器,打开/etc/munin/plugin-conf.d/munin-node 增加以下内容(如果不存在)

[nginx_*]
env.url http://localhost/nginx_status

 

如果你的Nginx不是跑在80端口上或者绑定的是其他的域名请自行修改env.url

现在来更新Munin-node的插件

执行 munin-node-configure –suggest –shell | bash -x 将会自动链接Nginx插件.

[root@jp02 ~]# munin-node-configure --suggest --shell | bash -x
# The following plugins caused errors:
# http_loadtime:
# 	Junk printed to stderr
# pgbouncer_connections:
# 	Junk printed to stderr
# pgbouncer_requests:
# 	Junk printed to stderr
# postgres_autovacuum:
# 	Non-zero exit during autoconf (255)
# postgres_bgwriter:
# 	Non-zero exit during autoconf (255)
# postgres_cache_:
# 	Non-zero exit during autoconf (255)
# postgres_checkpoints:
# 	Non-zero exit during autoconf (255)
# postgres_connections_:
# 	Non-zero exit during autoconf (255)
# postgres_connections_db:
# 	Non-zero exit during autoconf (255)
# postgres_locks_:
# 	Non-zero exit during autoconf (255)
# postgres_oldest_prepared_xact_:
# 	Non-zero exit during autoconf (255)
# postgres_prepared_xacts_:
# 	Non-zero exit during autoconf (255)
# postgres_querylength_:
# 	Non-zero exit during autoconf (255)
# postgres_scans_:
# 	Non-zero exit during autoconf (255)
# postgres_size_:
# 	Non-zero exit during autoconf (255)
# postgres_transactions_:
# 	Non-zero exit during autoconf (255)
# postgres_tuples_:
# 	Non-zero exit during autoconf (255)
# postgres_users:
# 	Non-zero exit during autoconf (255)
# postgres_xlog:
# 	Non-zero exit during autoconf (255)
# proc:
# 	In family 'auto' but doesn't have 'autoconf' capability
# redis_:
# 	Junk printed to stderr
# slony_lag_:
# 	Junk printed to stderr
+ ln -s /usr/share/munin/plugins/nginx_request /etc/munin/plugins/nginx_request
+ ln -s /usr/share/munin/plugins/nginx_status /etc/munin/plugins/nginx_status

 

最后,重启Munin-node

sudo systemctl restart munin-node

 

稍等片刻之后即可在Munin的页面中看到Nginx的图表