Purging Expired Tokens Generated By The Registration – 清除由注册产生的过期令牌

最后修改: 2016年 5月 27日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial – we’re continuing the ongoing Registration with Spring Security series to setup a scheduled task to purge expired VerificationTokens. During the registration process a VerificationToken is persisted. In this article we will show how to remove these entities.

在本教程中,我们将继续正在进行的用Spring Security进行注册系列来设置一个计划任务来清除过期的VerificationTokens。在注册过程中,VerificationToken被持久化。在这篇文章中,我们将展示如何删除这些实体。

2. Removing an Expired Token

2.删除过期的代币

Recall from the prior article in the series that a verification token has the member expiryDate, representing the expiration timestamp for the token:

回顾系列文章中的,验证令牌的成员expiryDate,代表令牌的到期时间戳。

@Entity
public class VerificationToken {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String token;

    @OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
    @JoinColumn(nullable = false, name = "user_id", 
      foreignKey = @ForeignKey(name="FK_VERIFY_USER"))
    private User user;

    private Date expiryDate;
    ...
}

We’ll use this expiryDate property to generate a query with Spring Data.

我们将使用这个expiryDate属性,用Spring Data生成一个查询。

If you’re looking for more info on Spring Data JPA, have a look at this article.

如果您正在寻找有关Spring Data JPA的更多信息,请看这篇文章

2.1. The Delete Operation

2.1.删除操作

To facilitate the token removal we’ll add a new method to our VerificationTokenRepository for deleting expired tokens:

为了方便删除令牌,我们将为我们的VerificationTokenRepository添加一个新方法,用于删除过期的令牌。

public interface VerificationTokenRepository
  extends JpaRepository<VerificationToken, Long> {

    void deleteByExpiryDateLessThan(Date now);
}

The use of the query keyword LessThan indicates to Spring Data’s query creation mechanism that we are only interested in tokens whose expiryDate property is less than the specified time.

使用查询关键字 LessThan向Spring Data的查询创建机制表明,我们只对expiryDate属性小于指定时间的令牌感兴趣。

Note that because VerificationToken has a @OneToOne association with User marked with FetchType.EAGER, a select is also issued to populate the User entity— even though the signature of deleteByExpiryDateLessThan has the return type void:

请注意,因为VerificationTokenUser@OneToOne关联,并标有FetchType.EAGER,所以也会发出一个选择来填充User实体–尽管deleteByExpiryDateLessThan的签名有返回类型void

select 
    *
from 
    VerificationToken verification 
where 
    verification.expiryDate < ?

select 
    * 
from
    user_account user 
where
    user.id=?

delete from 
    VerificationToken
where
    id=?

2.2. The Delete With JPQL

2.2.用JPQL删除

Alternatively, we can create a JPQL query if we do not have a need to load the entities into the persistence context:

另外,如果我们不需要将实体加载到持久化上下文中,我们可以创建一个JPQL查询。

public interface VerificationTokenRepository
  extends JpaRepository<VerificationToken, Long> {

    @Modifying
    @Query("delete from VerificationToken t where t.expiryDate <= ?1")
    void deleteAllExpiredSince(Date now);
}

And Hibernate will not load the entities into the persistence context:

而Hibernate不会将实体加载到持久化上下文中。

delete from
    VerificationToken
where
    expiryDate <= ?

3. Scheduling a Token Purge Task

3.调度令牌清理任务

We now have a query we want to execute periodically; We’ll use the scheduling support in Spring and create a method to run our delete logic.

我们现在有一个要定期执行的查询;我们将使用Spring中的调度支持并创建一个方法来运行我们的删除逻辑。

If you’re looking for more info on the Spring Job Scheduling framework, have a look at this article.

如果您正在寻找有关Spring Job Scheduling框架的更多信息,请看这篇文章

3.1. Enable Scheduling

3.1.启用调度功能

To enable the scheduling of tasks we create a new configuration class SpringTaskConfig annotated with @EnableScheduling:

为了启用任务的调度,我们创建了一个新的配置类SpringTaskConfig,用@EnableScheduling注释。

@Configuration
@EnableScheduling
public class SpringTaskConfig {
    //
}

3.2. Purge Token Task

3.2.清除令牌任务

In the service layer we call our repository with the current time.

在服务层,我们用当前时间调用我们的存储库。

We then annotate the method with @Scheduled to indicate that Spring should execute it periodically:

然后我们用@Scheduled注解该方法,以表明Spring应该定期执行该方法。

@Service
@Transactional
public class TokensPurgeTask {

    @Autowired
    private VerificationTokenRepository tokenRepository;

    @Scheduled(cron = "${purge.cron.expression}")
    public void purgeExpired() {
        Date now = Date.from(Instant.now());
        tokenRepository.deleteAllExpiredSince(now);
    }
}

3.3. The Schedule

3.3.时间表

We used a property to hold the value of the crontab settings to avoid recompilation when changed. In the application.properties we assign the value:

我们用一个属性来保持crontab设置的值,以避免改变时重新编译。在application.properties中,我们指定了这个值。

#    5am every day
purge.cron.expression=0 0 5 * * ?

4. Conclusion

4.结论

In this article we solved the removal of VerificationTokens using Spring Data JPA.

在这篇文章中,我们使用Spring Data JPA解决了删除VerificationTokens的问题。

We demonstrated query creation using a property expression to find all tokens having an expiration date less than a specified time. And we created a task to invoke this clean logic at runtime – and registered it with the Spring Job Scheduling framework to be executed periodically.

我们演示了使用属性表达式创建查询,以找到所有有效期小于指定时间的令牌。我们创建了一个任务,在运行时调用这个干净的逻辑–并在Spring Job Scheduling框架下注册,以便定期执行。

The implementation of this Registration with Spring Security tutorial can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.

github项目中可以找到该注册教程的实现 – 这是一个基于Eclipse的项目,因此应该很容易导入并按原样运行。