Redis——内存管理

一、内存管理:

命令

作用

expire key seconds

设置超时时间戳,单位为秒

ttl key

查看超时时间,-1表示没有超时时间,-2表示已经超时

persist key

持久化key,取消超时时间

  1、redis-cli:

    

  2、spring操作:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:redis.xml")
public class RedisTest {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testExpireTime() {
        redisTemplate.execute(new SessionCallback() {
            public Object execute(RedisOperations operations) throws DataAccessException {

                ValueOperations ops = operations.opsForValue();
                ops.set("myhome", "China");
                operations.expire("myhome", 100, TimeUnit.SECONDS);
                Long time = operations.getExpire("myhome");
                System.out.println(time);
                operations.persist("myhome");
                Long time1 = operations.getExpire("myhome");
                System.out.println(time1);

                return null;
            }
        });
    }
}

二、内存回收策略:

  1、超时后不会自动回收,只会标记键已经超时;

  2、惰性回收:get命令会回收已经超时的键;

  3、redis.conf:中配置hz 1~100;

    //hz为回收频率:建议配置为10;  

    

  4、精准回收:maxmemory-samples 1~10

    //10:最精致,最慢;1:最不精准,最快;

    

  5、maxmemory:配置最大内存,键内存超过这个最大值 ,直接使用LRU算法回收;

  5、回收算法:

    maxmemory-policy:noeviction  //默认

    

Volatile-lru

采用最近使用最少的淘汰策略,Redis将回收那些超时的键值对

Allkeys-lru

Redis将对所有的键值对,采用最近最少使用的策略进行淘汰

Volatile-random

采用随机淘汰策略删除超时的键值对

Allkeys-random

采用随机淘汰策略删除所有的键值对

Volatile-ttl

采用删除存活时间最短的键值对策略

Noeviction

不淘汰任何键值对,当内存已满,只支持读,不支持写

  //redis默认使用的是none算法,但是使用get会惰性回收;

  //建议使用Volatile-lru和Allkeys-lru算法;

   

猜你喜欢

转载自www.cnblogs.com/Tractors/p/11285692.html