ehcache实现用户登陆失败5次锁定5分钟不能登陆

                                           登陆失败5次锁定账号5分钟

本人使用环境是springboot+ ehcache

如果还有不会springboot的童鞋看下我这篇文章 hello springBoot

登陆失败前4次提示用户密码错误,第5次把用户账号存入缓存,并清除计数的缓存,运行效果如下,代码在下面

使用环境配置

第1步:引入ehcache依赖包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ljm</groupId>
    <artifactId>ehcache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>ehcache</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--eacache缓存需要的2个包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

第2步: 在resource添加ehcache.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <diskStore path="java.io.tmpdir/Tmp_EhCache"/>
    <!--默认缓存 -->
    <defaultCache
            eternal="false"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="300"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"/>
    <!--用户锁定5分钟缓存-->
    <cache
            name="userCache"
            eternal="false"
            maxElementsInMemory="100"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="300"
            memoryStoreEvictionPolicy="LRU"/>

    <!--登陆失败次数缓存-->
    <cache
            name="countCache"
            eternal="false"
            maxElementsInMemory="100"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="0"
            memoryStoreEvictionPolicy="LRU"/>
</ehcache>

        <!-- maxElementsInMemory 内存中最大缓存对象数,看着自己的heap大小来搞 -->
        <!-- eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false -->
        <!-- maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大 -->
        <!-- overflowToDisk:true表示当内存缓存的对象数目达到了maxElementsInMemory界限后,
        会把溢出的对象写到硬盘缓存中。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行。-->
        <!-- diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。-->
        <!-- diskPersistent:是否缓存虚拟机重启期数据 -->
        <!-- diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒 -->

        <!-- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,
        如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,
        EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,
        则表示对象可以无限期地处于空闲状态 -->

        <!-- timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,
        如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,
        EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,
        则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义 -->

        <!-- memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,
        Ehcache将会根据指定的策略去清理内存。可选策略有:LRU(最近最少使用,默认策略)、
        FIFO(先进先出)、LFU(最少访问次数)。-->

第3步:在application.properties配置文件中配置ehcache

# tomcat 配置
server.port=8080
# 配置ehcache缓存
spring.cache.type=ehcache
# 指定ehcache配置文件路径
spring.cache.ehcache.config=classpath:/ehcache.xml

第4步:添加对缓存操作的类

package com.ljm.ehcache.server;

/**
 * @author lijunming
 * @date 2018/8/18 下午10:11
 */
public interface UserCache {

    /**
     * 根据用户账号查询账号是否被锁定
     * @param userName
     * @return 锁定返回 true,否则 false
     */
    boolean  get(String userName);

    /**
     * 用户登陆失败,往缓存中记录失败的次数,次数到5次,锁定账号
     * @param userName
     * @return 次数达到5次返回true,否则false
     */
    boolean  put(String userName);

}
package com.ljm.ehcache.server.impl;
import com.ljm.ehcache.server.UserCache;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author lijunming
 * @date 2018/8/18 下午10:11
 */
@Component
public class UserCacheImpl implements UserCache {
    @Resource
    private CacheManager cacheManager;

    @Override
    public boolean get(String userName) {
        Cache userCache = cacheManager.getCache("userCache");
        String user = userCache.get(userName, String.class);
        if (user == null) {
            return false;
        }
        return true;
    }

    @Override
    public boolean put(String userName) {
        Cache countCache = cacheManager.getCache("countCache");
        Integer count = countCache.get(userName, Integer.class);
        if (count != null) {
            if (count == 4) {
                Cache userCache = cacheManager.getCache("userCache");
                userCache.put(userName,"look");
                countCache.evict(userName);//重计数缓存移除当前用户计数
                return true;
            } else {
                countCache.put(userName, ++count);
            }
        } else {
            countCache.put(userName, 1);
        }
        return false;
    }

}

第5步,添加测试用的controller

package com.ljm.ehcache.controller;

import com.ljm.ehcache.server.UserCache;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lijunming
 * @date 2018/8/19 上午1:06
 */
@RestController
public class LoginController {

    @Resource
    private UserCache userCache;

    @RequestMapping("/login")
    public Map login(@RequestBody Map map){
        String userName=map.get("userName").toString();
        boolean flag=userCache.get(userName);
        Map resultMap=new HashMap();
        if(flag){
            resultMap.put("success",false);
            resultMap.put("message","用户已被锁定,请5分钟后登陆!");
            return resultMap;
        }
        String password=map.get("password").toString();
        String message="";
        boolean success=false;
        if(!password.equals("1995")){
            boolean isLook=userCache.put(userName);
            if(isLook){
                message="连续输错5次密码,账号已被锁定";
            }else{
                message="密码错误,请重新输入!";
            }
        }else{
            message="登陆成功";
            success=true;
        }
        resultMap.put("success",success);
        resultMap.put("message",message);
        return resultMap;
    }
}

如过配置过程有问题的朋友可以连续我,邮箱: [email protected]

猜你喜欢

转载自blog.csdn.net/ming19951224/article/details/81814709
今日推荐