Spring Boot中使用Spring Security进行安全控制

转载来源http://blog.csdn.net/qq_26562641/article/details/53332458

准备工作

首先,构建一个简单的Web工程,以用于后续添加安全控制,也可以用之前Chapter3-1-2做为基础工程。若对如何使用spring Boot构建Web应用,可以先阅读《Spring Boot开发Web应用》一文。

Web层实现请求映射
     
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
     
     
@Controller
public class HelloController {
@RequestMapping( "/")
public String index() {
return "index";
}
@RequestMapping( "/hello")
public String hello() {
return "hello";
}
}
  • /:映射到index.html
  • /hello:映射到hello.html
实现映射的页面
  • src/main/resources/templates/index.html
     
     
1
2
3
4
5
6
7
8
9
10
     
     
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security入门 </title>
</head>
<body>
<h1>欢迎使用Spring Security! </h1>
<p>点击 <a th:href="@{/hello}">这里 </a> 打个招呼吧 </p>
</body>
</html>
  • src/main/resources/templates/hello.html
     
     
1
2
3
4
5
6
7
8
9
10
     
     
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec= "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World! </title>
</head>
<body>
<h1>Hello world! </h1>
</body>
</html>

可以看到在index.html中提供到/hello的链接,显然在这里没有任何安全控制,所以点击链接后就可以直接跳转到hello.html页面。

整合Spring Security

在这一节,我们将对/hello页面进行权限控制,必须是授权用户才能访问。当没有权限的用户访问后,跳转到登录页面。

添加依赖

在pom.xml中添加如下配置,引入对Spring Security的依赖。

     
     
1
2
3
4
5
6
7
8
     
     
<dependencies>
...
<dependency>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-security </artifactId>
</dependency>
...
</dependencies>
Spring Security配置

创建Spring Security的配置类WebSecurityConfig,具体如下:

     
     
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
     
     
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers( "/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage( "/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser( "user").password( "password").roles( "USER");
}
}
  • 通过@EnableWebSecurity注解开启Spring Security的功能
  • 继承WebSecurityConfigurerAdapter,并重写它的方法来设置一些web安全的细节
  • configure(HttpSecurity http)方法
    • 通过authorizeRequests()定义哪些URL需要被保护、哪些不需要被保护。例如以上代码指定了//home不需要任何认证就可以访问,其他的路径都必须通过身份验证。
    • 通过formLogin()定义当需要用户登录时候,转到的登录页面。
  • configureGlobal(AuthenticationManagerBuilder auth)方法,在内存中创建了一个用户,该用户的名称为user,密码为password,用户角色为USER。
新增登录请求与页面

在完成了Spring Security配置之后,我们还缺少登录的相关内容。

HelloController中新增/login请求映射至login.html

     
     
1
2
3
4
5
6
7
8
9
10
11
     
     
@Controller
public class HelloController {
// 省略之前的内容...
@RequestMapping( "/login")
public String login() {
return "login";
}
}

新增登录页面:src/main/resources/templates/login.html

     
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
     
     
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th= "http://www.thymeleaf.org"
xmlns:sec= "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
用户名或密码错
</div>
<div th:if="${param.logout}">
您已注销成功
</div>
<form th:action="@{/login}" method="post">
<div> <label> 用户名 : <input type="text" name="username"/> </label> </div>
<div> <label> 密 码 : <input type="password" name="password"/> </label> </div>
<div> <input type="submit" value="登录"/> </div>
</form>
</body>
</html>

可以看到,实现了一个简单的通过用户名和密码提交到/login的登录方式。

根据配置,Spring Security提供了一个过滤器来拦截请求并验证用户身份。如果用户身份认证失败,页面就重定向到/login?error,并且页面中会展现相应的错误信息。若用户想要注销登录,可以通过访问/login?logout请求,在完成注销之后,页面展现相应的成功消息。

到这里,我们启用应用,并访问http://localhost:8080/,可以正常访问。但是访问http://localhost:8080/hello的时候被重定向到了http://localhost:8080/login页面,因为没有登录,用户没有访问权限,通过输入用户名user和密码password进行登录后,跳转到了Hello World页面,再也通过访问http://localhost:8080/login?logout,就可以完成注销操作。

为了让整个过程更完成,我们可以修改hello.html,让它输出一些内容,并提供“注销”的链接。

     
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
     
     
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec= "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World! </title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]! </h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="注销"/>
</form>
</body>
</html>

本文通过一个最简单的示例完成了对Web应用的安全控制,Spring Security提供的功能还远不止于此,更多Spring Security的使用可参见Spring Security Reference

Spring Boot中的事务管理

什么是事务?

我们在开发企业应用时,对于业务人员的一个操作实际是对数据读写的多步操作的结合。由于数据操作在顺序执行的过程中,任何一步操作都有可能发生异常,异常会导致后续操作无法完成,此时由于业务逻辑并未正确的完成,之前成功操作数据的并不可靠,需要在这种情况下进行回退。

事务的作用就是为了保证用户的每一个操作都是可靠的,事务中的每一步操作都必须成功执行,只要有发生异常就回退到事务开始未进行操作的状态。

事务管理是Spring框架中最为常用的功能之一,我们在使用Spring Boot开发应用时,大部分情况下也都需要使用事务。

快速入门

在Spring Boot中,当我们使用了spring-boot-starter-jdbc或spring-boot-starter-data-jpa依赖的时候,框架会自动默认分别注入DataSourceTransactionManager或JpaTransactionManager。所以我们不需要任何额外配置就可以用@Transactional注解进行事务的使用。

我们以之前实现的《用spring-data-jpa访问数据库》的示例Chapter3-2-2作为基础工程进行事务的使用常识。

在该样例工程中(若对该数据访问方式不了解,可先阅读该文章),我们引入了spring-data-jpa,并创建了User实体以及对User的数据访问对象UserRepository,在ApplicationTest类中实现了使用UserRepository进行数据读写的单元测试用例,如下:

      
      
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
      
      
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {
@Autowired
private UserRepository userRepository;
@Test
public void test() throws Exception {
// 创建10条记录
userRepository.save( new User( "AAA", 10));
userRepository.save( new User( "BBB", 20));
userRepository.save( new User( "CCC", 30));
userRepository.save( new User( "DDD", 40));
userRepository.save( new User( "EEE", 50));
userRepository.save( new User( "FFF", 60));
userRepository.save( new User( "GGG", 70));
userRepository.save( new User( "HHH", 80));
userRepository.save( new User( "III", 90));
userRepository.save( new User( "JJJ", 100));
// 省略后续的一些验证操作
}
}

可以看到,在这个单元测试用例中,使用UserRepository对象连续创建了10个User实体到数据库中,下面我们人为的来制造一些异常,看看会发生什么情况。

通过定义User的name属性长度为5,这样通过创建时User实体的name属性超长就可以触发异常产生。

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
      
      
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, length = 5)
private String name;
@Column(nullable = false)
private Integer age;
// 省略构造函数、getter和setter
}

修改测试用例中创建记录的语句,将一条记录的name长度超过5,如下:name为HHHHHHHHH的User对象将会抛出异常。

      
      
1
2
3
4
5
6
7
8
9
10
11
12
      
      
// 创建10条记录
userRepository.save( new User( "AAA", 10));
userRepository.save( new User( "BBB", 20));
userRepository.save( new User( "CCC", 30));
userRepository.save( new User( "DDD", 40));
userRepository.save( new User( "EEE", 50));
userRepository.save( new User( "FFF", 60));
userRepository.save( new User( "GGG", 70));
userRepository.save( new User( "HHHHHHHHHH", 80));
userRepository.save( new User( "III", 90));
userRepository.save( new User( "JJJ", 100));

执行测试用例,可以看到控制台中抛出了如下异常,name字段超长:

      
      
1
2
3
4
5
6
      
      
2016-05-27 10:30:35.948 WARN 2660 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1406, SQLState: 22001
2016-05-27 10:30:35.948 ERROR 2660 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Data truncation: Data too long for column 'name' at row 1
2016-05-27 10:30:35.951 WARN 2660 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 1406, SQLState: HY000
2016-05-27 10:30:35.951 WARN 2660 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Data too long for column 'name' at row 1
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.DataException: could not execute statement

此时查数据库中,创建了name从AAA到GGG的记录,没有HHHHHHHHHH、III、JJJ的记录。而若这是一个希望保证完整性操作的情况下,AAA到GGG的记录希望能在发生异常的时候被回退,这时候就可以使用事务让它实现回退,做法非常简单,我们只需要在test函数上添加@Transactional注解即可。

      
      
1
2
3
4
5
6
7
      
      
@Test
@Transactional
public void test() throws Exception {
// 省略测试内容
}

再来执行该测试用例,可以看到控制台中输出了回滚日志(Rolled back transaction for test context),

      
      
1
2
3
4
5
6
7
      
      
2016-05-27 10:35:32.210 WARN 5672 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1406, SQLState: 22001
2016-05-27 10:35:32.210 ERROR 5672 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Data truncation: Data too long for column 'name' at row 1
2016-05-27 10:35:32.213 WARN 5672 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 1406, SQLState: HY000
2016-05-27 10:35:32.213 WARN 5672 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Data too long for column 'name' at row 1
2016-05-27 10:35:32.221 INFO 5672 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test context [DefaultTestContext@1d7a715 testClass = ApplicationTests, testInstance = com.didispace.ApplicationTests@95a785, testMethod = test@ApplicationTests, testException = org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.DataException: could not execute statement, mergedContextConfiguration = [MergedContextConfiguration@11f39f9 testClass = ApplicationTests, locations = '{}', classes = '{class com.didispace.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]].
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.DataException: could not execute statement

再看数据库中,User表就没有AAA到GGG的用户数据了,成功实现了自动回滚。

这里主要通过单元测试演示了如何使用@Transactional注解来声明一个函数需要被事务管理,通常我们单元测试为了保证每个测试之间的数据独立,会使用@Rollback注解让每个单元测试都能在结束时回滚。而真正在开发业务逻辑时,我们通常在service层接口中使用@Transactional来对各个业务逻辑进行事务管理的配置,例如:

      
      
1
2
3
4
5
6
7
      
      
public interface UserService {
@Transactional
User login(String name, String password);
}

事务详解

上面的例子中我们使用了默认的事务配置,可以满足一些基本的事务需求,但是当我们项目较大较复杂时(比如,有多个数据源等),这时候需要在声明事务时,指定不同的事务管理器。对于不同数据源的事务管理配置可以见《Spring Boot多数据源配置与使用》中的设置。在声明事务时,只需要通过value属性指定配置的事务管理器名即可,例如:@Transactional(value="transactionManagerPrimary")

除了指定不同的事务管理器之后,还能对事务进行隔离级别和传播行为的控制,下面分别详细解释:

#### 隔离级别

隔离级别是指若干个并发的事务之间的隔离程度,与我们开发时候主要相关的场景包括:脏读取、重复读、幻读。

我们可以看org.springframework.transaction.annotation.Isolation枚举类中定义了五个表示隔离级别的值:

      
      
1
2
3
4
5
6
7
      
      
public enum Isolation {
DEFAULT(- 1),
READ_UNCOMMITTED( 1),
READ_COMMITTED( 2),
REPEATABLE_READ( 4),
SERIALIZABLE( 8);
}
  • DEFAULT:这是默认值,表示使用底层数据库的默认隔离级别。对大部分数据库而言,通常这值就是:READ_COMMITTED
  • READ_UNCOMMITTED:该隔离级别表示一个事务可以读取另一个事务修改但还没有提交的数据。该级别不能防止脏读和不可重复读,因此很少使用该隔离级别。
  • READ_COMMITTED:该隔离级别表示一个事务只能读取另一个事务已经提交的数据。该级别可以防止脏读,这也是大多数情况下的推荐值。
  • REPEATABLE_READ:该隔离级别表示一个事务在整个过程中可以多次重复执行某个查询,并且每次返回的记录都相同。即使在多次查询之间有新增的数据满足该查询,这些新增的记录也会被忽略。该级别可以防止脏读和不可重复读。
  • SERIALIZABLE:所有的事务依次逐个执行,这样事务之间就完全不可能产生干扰,也就是说,该级别可以防止脏读、不可重复读以及幻读。但是这将严重影响程序的性能。通常情况下也不会用到该级别。

指定方法:通过使用isolation属性设置,例如:

      
      
1
      
      
@Transactional(isolation = Isolation.DEFAULT)
传播行为

所谓事务的传播行为是指,如果在开始当前事务之前,一个事务上下文已经存在,此时有若干选项可以指定一个事务性方法的执行行为。

我们可以看org.springframework.transaction.annotation.Propagation枚举类中定义了6个表示传播行为的枚举值:

      
      
1
2
3
4
5
6
7
8
9
      
      
public enum Propagation {
REQUIRED( 0),
SUPPORTS( 1),
MANDATORY( 2),
REQUIRES_NEW( 3),
NOT_SUPPORTED( 4),
NEVER( 5),
NESTED( 6);
}
  • REQUIRED:如果当前存在事务,则加入该事务;如果当前没有事务,则创建一个新的事务。
  • SUPPORTS:如果当前存在事务,则加入该事务;如果当前没有事务,则以非事务的方式继续运行。
  • MANDATORY:如果当前存在事务,则加入该事务;如果当前没有事务,则抛出异常。
  • REQUIRES_NEW:创建一个新的事务,如果当前存在事务,则把当前事务挂起。
  • NOT_SUPPORTED:以非事务方式运行,如果当前存在事务,则把当前事务挂起。
  • NEVER:以非事务方式运行,如果当前存在事务,则抛出异常。
  • NESTED:如果当前存在事务,则创建一个事务作为当前事务的嵌套事务来运行;如果当前没有事务,则该取值等价于REQUIRED

指定方法:通过使用propagation属性设置,例如:

      
      
1
      
      
@Transactional(propagation = Propagation.REQUIRED)

Spring Boot中使用log4j实现http请求日志入mongodb

准备工作

可以先拿Chapter4-2-4工程为基础,进行后续的实验改造。该工程实现了一个简单的REST接口,一个对web层的切面,并在web层切面前后记录http请求的日志内容。

通过自定义appender实现

思路:log4j提供的输出器实现自Appender接口,要自定义appender输出到MongoDB,只需要继承AppenderSkeleton类,并实现几个方法即可完成。

引入mongodb的驱动

在pom.xml中引入下面依赖

      
      
1
2
3
4
5
      
      
<dependency>
<groupId>org.mongodb </groupId>
<artifactId>mongodb-driver </artifactId>
<version>3.2.2 </version>
</dependency>
实现MongoAppender

编写MongoAppender类继承AppenderSkeleton,实现如下:

      
      
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
      
      
public class MongoAppender extends AppenderSkeleton {
private MongoClient mongoClient;
private MongoDatabase mongoDatabase;
private MongoCollection<BasicDBObject> logsCollection;
private String connectionUrl;
private String databaseName;
private String collectionName;
@Override
protected void append(LoggingEvent loggingEvent) {
if(mongoDatabase == null) {
MongoClientURI connectionString = new MongoClientURI(connectionUrl);
mongoClient = new MongoClient(connectionString);
mongoDatabase = mongoClient.getDatabase(databaseName);
logsCollection = mongoDatabase.getCollection(collectionName, BasicDBObject.class);
}
logsCollection.insertOne((BasicDBObject) loggingEvent.getMessage());
}
@Override
public void close() {
if(mongoClient != null) {
mongoClient.close();
}
}
@Override
public boolean requiresLayout() {
return false;
}
// 省略getter和setter
}
  • 定义MongoDB的配置参数,可通过log4j.properties配置:

    • connectionUrl:连接mongodb的串
    • databaseName:数据库名
    • collectionName:集合名
  • 定义MongoDB的连接和操作对象,根据log4j.properties配置的参数初始化:

    • mongoClient:mongodb的连接客户端
    • mongoDatabase:记录日志的数据库
    • logsCollection:记录日志的集合
  • 重写append函数:

    • 根据log4j.properties中的配置创建mongodb连接
    • LoggingEvent提供getMessage()函数来获取日志消息
    • 往配置的记录日志的collection中插入日志消息
  • 重写close函数:关闭mongodb的

配置log4j.properties

设置名为mongodb的logger:

  • 记录INFO级别日志
  • appender实现为com.didispace.log.MongoAppende
  • mongodb连接地址:mongodb://localhost:27017
  • mongodb数据库名:logs
  • mongodb集合名:logs_request
      
      
1
2
3
4
5
6
      
      
log4j.logger.mongodb=INFO, mongodb
# mongodb输出
log4j.appender.mongodb=com.didispace.log.MongoAppender
log4j.appender.mongodb.connectionUrl=mongodb://localhost:27017
log4j.appender.mongodb.databaseName=logs
log4j.appender.mongodb.collectionName=logs_request
切面中使用mongodb logger

修改后的代码如下,主要做了以下几点修改:

  • logger取名为mongodb的
  • 通过getBasicDBObject函数从HttpServletRequest和JoinPoint对象中获取请求信息,并组装成BasicDBObject
    • getHeadersInfo函数从HttpServletRequest中获取header信息
  • 通过logger.info(),输出BasicDBObject对象的信息到mongodb
      
      
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
      
      
@Aspect
@Order( 1)
@Component
public class WebLogAspect {
private Logger logger = Logger.getLogger( "mongodb");
@Pointcut( "execution(public * com.didispace.web..*.*(..))")
public void webLog(){}
@Before( "webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 获取HttpServletRequest
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 获取要记录的日志内容
BasicDBObject logInfo = getBasicDBObject(request, joinPoint);
logger.info(logInfo);
}
private BasicDBObject getBasicDBObject(HttpServletRequest request, JoinPoint joinPoint) {
// 基本信息
BasicDBObject r = new BasicDBObject();
r.append( "requestURL", request.getRequestURL().toString());
r.append( "requestURI", request.getRequestURI());
r.append( "queryString", request.getQueryString());
r.append( "remoteAddr", request.getRemoteAddr());
r.append( "remoteHost", request.getRemoteHost());
r.append( "remotePort", request.getRemotePort());
r.append( "localAddr", request.getLocalAddr());
r.append( "localName", request.getLocalName());
r.append( "method", request.getMethod());
r.append( "headers", getHeadersInfo(request));
r.append( "parameters", request.getParameterMap());
r.append( "classMethod", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
r.append( "args", Arrays.toString(joinPoint.getArgs()));
return r;
}
private Map<String, String> getHeadersInfo(HttpServletRequest request) {
Map<String, String> map = new HashMap<>();
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
map.put(key, value);
}
return map;
}
}

完整示例:Chapter4-2-5

其他补充

上述内容主要提供一个思路去实现自定义日志的输出和管理。我们可以通过jdbc实现日志记录到mongodb,也可以通过spring-data-mongo来记录到mongodb,当然我们也可以输出到其他数据库,或者输出到消息队列等待其他后续处理等。

对于日志记录到mongodb,也可以直接使用log4mongo实现更为方便快捷。

MongoDB中的基础概念:Databases、Collections、Documents

MongoDB以BSON格式的文档(Documents)形式存储。Databases中包含集合(Collections),集合(Collections)中存储文档(Documents)。

BSON是一个二进制形式的JSON文档,它比JSON包含更多的数据类型。对于BSON规格,可参见bsonspec.org,也可参考BSON类型

Databases

在MongoDB中,databases保存文档(Documents)的集合(Collections)。

在Mongo Shell中,通过使用use <db>命令来选中database,就像下面的例子:

      
      
1
      
      
use myDB
创建Database

如果database不存在,MongoDB会在第一次为database存储数据的时候创建。因此,你可以直接切换到一个不存在的数据库,然后执行下面的语句:

      
      
1
2
3
      
      
use myNewDB
db.myNewCollection1.insert( { x: 1 } )

insert()操作会创建名为myNewDB的database和名为myNewCollection1的collection(如果他们不存在的话)。

Collections

MongoDB在collections中存储文档(documents)。Collections类似于关系型数据库中的表(tables)。

创建Collection

如果collection不存在,MongoDB会在第一次为collection存储数据的时候创建。

      
      
1
2
      
      
db.myNewCollection2.insert( { x: 1 } )
db.myNewCollection3.createIndex( { y: 1 } )

无论是insert()还是createIndex()操作,都会创建它们各自指定的收集,如果他们不存在的话。

显式创建

MongoDB提供db.createCollection()方法来显式创建一个collection,同时还能设置各种选项,例如:设置最大尺寸和文档校验规则。如果你没有指定这些选项,那么你就不需要显式创建collection,因为MongoDB会在你创建第一个数据的时候自动创建collection。

若要修改这些collection选择,可查看collMod

Documents校验

3.2.x版本新增内容。

默认情况下,collection不要求文档有相同的结构;例如,在一个collection的文档不必具有相同的fields,对于单个field在一个collection中的不同文档中可以是不同的数据类型。

从MongoDB 3.2开始,你可以在对collection进行update和insert操作的时候执行文档(documents)校验规则。具体可参见文档验证的详细信息

Documents

Document结构

MongoDB的文件是由field和value对的结构组成,例如下面这样的结构:

      
      
1
2
3
4
5
6
7
      
      
{
field1: value1,
field2: value2,
field3: value3,
...
fieldN: valueN
}

value值可以是任何BSON数据类型,包括:其他document,数字,和document数组。

例如下面的document,包含各种不同类型的值:

      
      
1
2
3
4
5
6
7
8
9
10
      
      
var mydoc = {
_id: ObjectId( "5099803df3f4948bd2f98391"),
name: {
first: "Alan", last: "Turing"
},
birth: new Date( 'Jun 23, 1912'),
death: new Date( 'Jun 07, 1954'),
contribs: [ "Turing machine", "Turing test", "Turingery" ],
views : NumberLong( 1250000)
}

上面例子中的各fields有下列数据类型:

  • _id:ObjectId类型
  • name:一个嵌入的document,包含first和last字段
  • birth和death:Date类型
  • contribs:字符串数组
  • views:NumberLong类型
Field名

Field名是一个字符串。

Documents中的filed名有下列限制:

  • _id被保留用于主键;其值必须是集合中唯一的、不可变的、并且可以是数组以外的任何数据类型
  • 不能以美元符号$开头
  • 不能包含点字符.
  • 不能包含空字符
Field Value限制

对于索引的collections,索引字段中的值有最大长度限制。详情请参见Maximum Index Key Length

圆点符号

MongoDB中使用圆点符号.访问数组中的元素,也可以访问嵌入式Documents的fields。

Arrays数组

通过圆点符号.来链接Arrays数组名字和从0开始的数字位置,来定位和访问一个元素数组:

      
      
1
      
      
"<array>.<index>"

举例:对于下面的document:

      
      
1
2
3
4
5
      
      
{
...
contribs: [ "Turing machine", "Turing test", "Turingery" ],
...
}

要访问contribs数组中的第三个元素,可以这样访问:

      
      
1
      
      
"contribs.2"
嵌入式Documents

通过圆点符号.来链接嵌入式document的名字和field名,来定位和访问嵌入式document:

      
      
1
      
      
"<embedded document>.<field>"

举例:对于下面的document:

      
      
1
2
3
4
5
      
      
{
...
name: { first: "Alan", last: "Turing" },
...
}

要访问name中的last字段,可以这样使用:

      
      
1
      
      
"name.last"
Documents限制

Documents有下面这些属性和限制:

Document大小限制

每个BSON文档的最大尺寸为16兆字节。

最大文档大小有助于确保一个单个文档不会使用过量的内存,或通信过程中过大的带宽占用。

若要存储超过最大尺寸的文档,MongoDB提供了GridFS API。可以看mongofiles和更多有关GridFS的文档

Document Field顺序

MongoDB中field的顺序默认是按照写操作的顺序来保存的,除了下面几种情况:

  • _id总是document的第一个field
  • 可能会导致文档中的字段的重新排序的更新,包括字段名重命名。

在2.6版本起,MongoDB开始积极地尝试保留document中field的顺序。

_id字段

_id字段有以下行为和限制:

  • 默认情况下,MongoDB会在创建collection时创建一个_id字段的唯一索引
  • _id字段总是documents中的第一个字段。如果服务器接收到一个docuement,它的第一个字段不是_id,那么服务器会将_id字段移在开头
  • _id字段可以是除了array数组之外的任何BSON数据格式

以下是存储_id值的常用选项:

  • 使用ObjectId
  • 最好使用自然的唯一标识符,可以节省空间并避免额外的索引
  • 生成一个自动递增的数字。请参阅创建一个自动递增序列字段
  • 在您的应用程序代码中生成UUID。为了更高效的在collection和_id索引中存储UUID值,可以用BSON的BinData类型存储UUID。

大部分MongoDB驱动客户端会包含_id字段,并且在发送insert操作的时候生成一个ObjectId。但是如果客户端发送一个不带_id字段的document,mongod会添加_id字段并产生一个ObjectId

Spring Boot中使用AOP统一处理Web请求日志


AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是Spring框架中的一个重要内容,它通过对既有程序定义一个切入点,然后在其前后切入不同的执行内容,比如常见的有:打开数据库连接/关闭数据库连接、打开事务/关闭事务、记录日志等。基于AOP不会破坏原来程序逻辑,因此它可以很好的对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

下面主要讲两个内容,一个是如何在Spring Boot中引入Aop功能,二是如何使用Aop做切面去统一处理Web请求的日志。

以下所有操作基于chapter4-2-2工程进行。

准备工作

因为需要对web请求做切面来记录日志,所以先引入web模块,并创建一个简单的hello请求的处理。

  • pom.xml中引入web模块
      
      
1
2
3
4
5
      
      
<dependency>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-web </artifactId>
</dependency>
  • 实现一个简单请求处理:通过传入name参数,返回“hello xxx”的功能。
      
      
1
2
3
4
5
6
7
8
9
10
11
      
      
@RestController
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
@ResponseBody
public String hello(@RequestParam String name) {
return "Hello " + name;
}
}

下面,我们可以对上面的/hello请求,进行切面日志记录。

引入AOP依赖

在Spring Boot中引入AOP就跟引入其他模块一样,非常简单,只需要在pom.xml中加入如下依赖:

      
      
1
2
3
4
5
      
      
<dependency>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-aop </artifactId>
</dependency>

在完成了引入AOP依赖包后,一般来说并不需要去做其他配置。也许在Spring中使用过注解配置方式的人会问是否需要在程序主类中增加@EnableAspectJAutoProxy来启用,实际并不需要。

可以看下面关于AOP的默认配置属性,其中spring.aop.auto属性默认是开启的,也就是说只要引入了AOP依赖后,默认已经增加了@EnableAspectJAutoProxy

      
      
1
2
3
4
5
      
      
# AOP
spring.aop.auto= true # Add @EnableAspectJAutoProxy.
spring.aop.proxy-target-class= false # Whether subclass-based (CGLIB) proxies are to be created (true) as
opposed to standard Java interface-based proxies ( false).

而当我们需要使用CGLIB来实现AOP的时候,需要配置spring.aop.proxy-target-class=true,不然默认使用的是标准Java的实现。

实现Web层的日志切面

实现AOP的切面主要有以下几个要素:

  • 使用@Aspect注解将一个java类定义为切面类
  • 使用@Pointcut定义一个切入点,可以是一个规则表达式,比如下例中某个package下的所有函数,也可以是一个注解等。
  • 根据需要在切入点不同位置的切入内容
    • 使用@Before在切入点开始处切入内容
    • 使用@After在切入点结尾处切入内容
    • 使用@AfterReturning在切入点return内容之后切入内容(可以用来对处理返回值做一些加工处理)
    • 使用@Around在切入点前后切入内容,并自己控制何时执行切入点自身的内容
    • 使用@AfterThrowing用来处理当切入内容部分抛出异常之后的处理逻辑
      
      
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
      
      
@Aspect
@Component
public class WebLogAspect {
private Logger logger = Logger.getLogger(getClass());
@Pointcut( "execution(public * com.didispace.web..*.*(..))")
public void webLog(){}
@Before( "webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
logger.info( "URL : " + request.getRequestURL().toString());
logger.info( "HTTP_METHOD : " + request.getMethod());
logger.info( "IP : " + request.getRemoteAddr());
logger.info( "CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info( "ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
logger.info( "RESPONSE : " + ret);
}
}

可以看上面的例子,通过@Pointcut定义的切入点为com.didispace.web包下的所有函数(对web层所有请求处理做切入点),然后通过@Before实现,对请求内容的日志记录(本文只是说明过程,可以根据需要调整内容),最后通过@AfterReturning记录请求返回的对象。

通过运行程序并访问:http://localhost:8080/hello?name=didi,可以获得下面的日志输出

      
      
1
2
3
4
5
6
7
      
      
2016-05-19 13:42:13,156 INFO WebLogAspect:41 - URL : http://localhost:8080/hello
2016-05-19 13:42:13,156 INFO WebLogAspect:42 - HTTP_METHOD : http://localhost:8080/hello
2016-05-19 13:42:13,157 INFO WebLogAspect:43 - IP : 0:0:0:0:0:0:0:1
2016-05-19 13:42:13,160 INFO WebLogAspect:44 - CLASS_METHOD : com.didispace.web.HelloController.hello
2016-05-19 13:42:13,160 INFO WebLogAspect:45 - ARGS : [didi]
2016-05-19 13:42:13,170 INFO WebLogAspect:52 - RESPONSE:Hello didi
优化:AOP切面中的同步问题

在WebLogAspect切面中,分别通过doBefore和doAfterReturning两个独立函数实现了切点头部和切点返回后执行的内容,若我们想统计请求的处理时间,就需要在doBefore处记录时间,并在doAfterReturning处通过当前时间与开始处记录的时间计算得到请求处理的消耗时间。

那么我们是否可以在WebLogAspect切面中定义一个成员变量来给doBefore和doAfterReturning一起访问呢?是否会有同步问题呢?

的确,直接在这里定义基本类型会有同步问题,所以我们可以引入ThreadLocal对象,像下面这样进行记录:

      
      
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
      
      
@Aspect
@Component
public class WebLogAspect {
private Logger logger = Logger.getLogger(getClass());
ThreadLocal<Long> startTime = new ThreadLocal<>();
@Pointcut( "execution(public * com.didispace.web..*.*(..))")
public void webLog(){}
@Before( "webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
startTime.set(System.currentTimeMillis());
// 省略日志记录内容
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
logger.info( "RESPONSE : " + ret);
logger.info( "SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
}
}
优化:AOP切面的优先级

由于通过AOP实现,程序得到了很好的解耦,但是也会带来一些问题,比如:我们可能会对Web层做多个切面,校验用户,校验头信息等等,这个时候经常会碰到切面的处理顺序问题。

所以,我们需要定义每个切面的优先级,我们需要@Order(i)注解来标识切面的优先级。i的值越小,优先级越高。假设我们还有一个切面是CheckNameAspect用来校验name必须为didi,我们为其设置@Order(10),而上文中WebLogAspect设置为@Order(5),所以WebLogAspect有更高的优先级,这个时候执行顺序是这样的:

  • @Before中优先执行@Order(5)的内容,再执行@Order(10)的内容
  • @After@AfterReturning中优先执行@Order(10)的内容,再执行@Order(5)的内容

所以我们可以这样子总结:

  • 在切入点前的操作,按order的值由小到大执行
  • 在切入点后的操作,按order的值由大到小执行

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值