redis使用场景

package com.leiyijia.demo.redis;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;

import lombok.Data;
import lombok.NoArgsConstructor;

@SpringBootApplication
@Component
public class RedisScene {
    
    @Resource(name = "redisTemplate")
    private RedisTemplate template;

    //计数器
    public long increment(String key, long num) {
        return template.opsForValue().increment(key, num);
    }
    
    //列表,返回列表长度
    public long add2List(String key, Object value) {
        return template.opsForList().leftPush(key, value);
    }
    //从左往右取出列表数据
    public List getList(String key, long start, long end) {
        return template.opsForList().range(key, start, end);
    }
    
    //给不重复的set集合添加数据,返回被添加的元素大小,不包括已经在set内的元素个数
    public long addSet(String key, Object value) {
        return template.opsForSet().add(key, value);
    }
    //获取计set中某个key的value集合
    public long countSet(String key) {
        return template.opsForSet().members(key).size();
    }
    
    //hash,存储对象
    public void addObject(String key, Object value) {
        template.opsForHash().put(key, key.hashCode(), value);
    }
    public Object getObject(String key) {
        return template.opsForHash().get(key, key.hashCode());
    }
    
    
    public static void main(String[] args) throws InterruptedException {
        ConfigurableApplicationContext context = SpringApplication.run(RedisScene.class, args);
        RedisScene scene = context.getBean(RedisScene.class);
        
        //用户1的粉丝数
        String key = "user:1:fans";
        System.out.println(scene.increment(key, 1));
        
        //用户1收藏的文章列表
        key = "user:1:arctiles";
        int article_id = 123;
        for(int i=0;i<20;i++)
            scene.add2List(key, article_id++);
        
        List subList = scene.getList(key,0,9);
        for(int i=0;i(User.class));
        scene.addObject(userKey, user);
        System.out.println(scene.getObject(userKey));
    }
    
    @Data
    @NoArgsConstructor
    static class User{
        private int userId;
        private String name;
    }
}

你可能感兴趣的:(redis使用场景)