search
HomeJavajavaTutorialDetailed analysis of the survival time (expire) of redis keys in Java

1. You can use the expire command in redis to set the survival time of a key. After the time is up, redis will automatically delete it
expire Set the survival time (unit/second)
pexpire Set the survival time (unit/millisecond)
ttl/pttl View the remaining survival time of the key
persist Cancel the survival time
expireat [key] unix timestamp 1351858600
pexpireat [key] unix timestamp (milliseconds) 1351858700000
2. Application scenarios
Limited-time promotions
Website data cache (for some data that needs to be updated regularly)
Limit the frequency of website visitor visits (for example: a maximum of 10 visits per minute)


    /** 
         * 限制网站访客访问频率(例如:1分钟最多访问10次),其中: 访客通过IP标识,即同一个IP在1分钟内仅能访问10次 
         */  
        @Test  
        public void test4(){  
              final String ip = "127.0.0.1" ;  
             Jedis redis = null;  
              //模拟同一个用户连续访问20次  
              for(int i =0;i <20;i ++){  
                  boolean t = validate(ip);  
                  if(t ){  
                     System. out.println("恭喜你,购票成功!" +i );  
                 } else{  
                      //获取当前ip过期时间  
                      redis = getRedis();  
                      break;  
                 }  
             }  
              while(true &&redis.ttl(ip)>0){  
                 System. out.println("抱歉,你访问过度频繁,请" +redis .ttl(ip )+"秒后再来访问!" );  
                  try {  
                     Thread. sleep(1000);  
                 } catch (InterruptedException e ) {  
                      e.printStackTrace();  
                 }  
             }  
             System. out.println("你可以再次访问了" );  
        }  
      
        /** 
         * 
         * @param ip 
         * @return  true: 可以访问,false: 表示已经达到最大上线 
         */  
        public boolean validate( String ip ) {  
             Jedis jedis = getRedis();  
             String value = jedis.get( ip);  
              if(value ==null||value.length()==0){ //第一次访问  
                  jedis.setex( ip, 60,String. valueOf(0));  
             } else{  
                  int v = Integer.parseInt (value );  
                  if(v >=10){  
                      return false ;  
                 }  
             }  
              jedis.incr( ip);  
              return true ;  
        }  
      
        /** 
         * @return 
         */  
        public Jedis getRedis() {  
              jedisPool = getJedisPool();  
             Jedis jedis = jedisPool.getResource();  
              return jedis ;  
        }  
      
        /** 
         * 
         */  
        public JedisPool getJedisPool() {  
             JedisPoolConfig poolConfig = new JedisPoolConfig();  
              // 控制一个pool最多有多少个 jedis实例。  
              poolConfig.setMaxTotal(1000);  
              // 控制一个pool最多有多少个状态为idle(空闲的)的 jedis实例。  
              poolConfig.setMaxIdle(10);  
              // 表示当borrow(引入)一个 jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;  
              poolConfig.setMaxWaitMillis(200000);  
              // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的 jedis实例均是可用的;  
              poolConfig.setTestOnBorrow(true);  
      
              return new JedisPool(poolConfig, host, port);  
        }

The above is the detailed content of Detailed analysis of the survival time (expire) of redis keys in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor