Redis使用详解

Redis是一个开源的支持网络可基于内存亦可持久化的日志型Key-Value数据库,并提供多种语言的API。它的值(value)可以是字符串(String)、哈希(Hash)、列表(list)、集合(sets)和有序集合(sorted sets)等类型。

一、Redis安装(以linux安装为例)

1.使用linux wget下载安装包

wget http://download.redis.io/releases/redis-3.0.0.tar.gz
2.将安装包拷贝到安装目录下如/usr/local

cp redis-3.0.0.rar.gz /usr/local
3.解压源码

tar -zxvf redis-3.0.0.tar.gz 
4.进入解压后的目录进行编译

cd /usr/local/redis-3.0.0
5.安装到指定目录如/usr/local/redis

make PREFIX=/usr/local/redis install
6.进入源码目录,里面有一份配置文件 redis.conf,然后将其拷贝到安装路径下

cp /usr/local/redis-3.0.0/redis.conf  /usr/local/redis
7.修改redis.conf配置文件, daemonize yes 以后端模式启动

vim /usr/local/redis/redis.conf


8.启动redis

cd /usr/local/redis
./bin/redis-server ./redis.conf
9.连接redis,查看现有redis密码

redis-cli
127.0.0.1:6379> config get requirepass
10.设置redis密码,成功后会返回“ok”字样

config set requirepass ****(****为你要设置的密码)
11.以密码登录redis

redis-cli -h 127.0.0.1 -p 6379 -a ****
二、SpringBoot配置使用redis

1.pom.xml添加redis依赖

 <!-- redis缓存 -->
 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>
2.application.properties添加数据源

#Redis 配置信息
#Redis数据库分片索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
3.配置RedisConfig配置文件

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
 
import java.lang.reflect.Method;
 
@Configuration
@EnableCaching//继承CachingConfigurerSupport并重写方法,配合该注解spring缓存框架的启用
public class RedisConfig extends CachingConfigurerSupport {
    /*
    载入通过配置文件配置的连接工厂
     */
    @Autowired
    private RedisConnectionFactory factory;
 
 
    /*
    重写缓存的key策略,可根据自身业务需要进行自己的配置生成条件
     */
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuffer sb = new StringBuffer();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
 
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory){
        RedisCacheManager rcm = RedisCacheManager.create(connectionFactory);
       return rcm;
    }
 
    /**
     * RedisTemplate配置
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());// key序列化
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer(this.getClass().getClassLoader()));// value序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());// Hash key序列化
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer(this.getClass().getClassLoader()));// Hash value序列化
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }
}
4.编写redis工具类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
 
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
@Component
public class RedisUtil {
 
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
 
    /*
    指定缓存失效时间
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /*
    根据key获取过期时间
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
 
    /*
    判断key是否存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
 
    /*
    删除缓存
     */
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }
 
    /*
    普通缓存获取
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
 
    /*
    普通缓存放入
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
 
    }
 
    /*
    普通缓存放入并设置过期时间
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /*
    递增
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }
 
   /*
   递减
    */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }
 
   /*
   HashGet
    */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
 
   /*
   获取hashKey对应的所有键值
    */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }
 
   /*
   HashSet
    */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /*
    HashSet并设置时间
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /*
    向一张hash表中放入数据,如果不存在将创建
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
   /*
   向一张hash表中放入数据,如果不存在将创建
    */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /*
    删除hash表中的值
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }
 
    /*
    判断hash表中是否有该项的值
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }
 
    /*
    hash递增,如果不存在,就会创建一个并把新增后的值返回
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }
 
   /*
   hash递减
    */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }
 
    /*
    根据key获取set中的所有值
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /*
    根据value从一个set中查询,是否存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /*
    将set数据放入缓存
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /*
    将set数据放入缓存并设置过期时间
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /*
    获取set缓存的长度
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /*
    移除值为value的
     */
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /*
    获取list缓存的内容
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
   /*
   获取list缓存的长度
    */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /*
    通过索引获取list中的值
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /*
    将list放入缓存
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /*
    将list放入缓存并设置过期时间
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /*
    将list放入缓存
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /*
    将list放入缓存并设置过期时间
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
   /*
   根据索引修改list中的某条数据
    */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /*
    移除N个值为value
     */
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
5.测试连接是否成功

public class RedisUtilTest extends BaseTest {
 
    @Autowired
    private RedisUtil redisUtil;
 
    @Test
    public void redisTest(){
        redisUtil.set("name","王二");
        System.out.println(redisUtil.get("name"));
        Map<String,Object> map=new HashMap<>();
        map.put("name", "张三");
        map.put("age", 24);
        map.put("address", "塞尔维亚666");
        redisUtil.hmset("15532002725", map,1000);
        System.out.println(redisUtil.hmget("15532002725"));
    }
}


6.shiro等其他程序中使用

//从redis缓存中查询缓存权限角色
String roleStr = stringRedisTemplate.opsForValue().get(userName);
if(roleStr!=null){
      roles= JSON.parseArray(roleStr.toString(),String.class);
 }else{
       //从数据库查询权限放到redis中
       roles=userService.getRoleByName(userName);
       stringRedisTemplate.opsForValue().set(userName,JSON.toJSONString(roles));
 }
 //设置超时时间
 stringRedisTemplate.expire(userName,TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
 
————————————————
from:https://blog.csdn.net/aliyacl/article/details/89150686

发布了176 篇原创文章 · 获赞 1 · 访问量 7140

猜你喜欢

转载自blog.csdn.net/qq_37769323/article/details/104216334