redis的安装与使用

一、安装redis

安装步骤:

首先安装gcc:yum install gcc-c++

第一步:redis的源码包上传到linux系统。

第二步:解压缩redis。

第三步:编译。进入redis源码目录。make

第四步:安装。make install PREFIX=/usr/local/redis

 

二、启动和关闭

前端启动:1)cd /usr/local/redis/bin/   2)./redis-server

后台启动:1)cp /usr/local/redis-3.0.0/redis.conf /usr/local/redis/bin/  

     2)修改redis.conf,将daemonize的值改为yes

       3)./redis-server redis.conf

可以通过kill 进程关闭或者运行./redis-cli shutdown

 

三、常见使用操作

连接redis:./redis-cli -h 192.168.25.128 -p 6379   连接redis防止乱码:./redis-cli --raw

带密码连接:./redis-cli -p 6379 -a <passwd>

设置密码:config set requirepass 123456  查看密码:config get requirepass

查看版本:./redis-server -v

常用命令:

keys *  hkeys hash1  set a 123  get a  del a  hset hash1 h 12  hget hash1 h  incr a  decr a

expire a 100:让a100秒后失效  ttl a:查看a还有多久失效  persist a:让a取消失效设置

zset命令:

1.添加5个元素到cus_order_set 中:zadd cus_order_set 112.0 user1 100.0 user2 123.0 user3 100.0 user4 33.0 user5

2.查询分数从小到大排列的所有数据:zrange cus_order_set 0 -1

3.查询前3大从大到小排列:zrevrange cus_order_set 0 2

4.查询user1的分数:zscore cus_order_set "user1"

5.查询user1的从大到小排名(返回0为最大):zrevrank cus_order_set "user1"

6.对user1的分数减1:zincrby cus_order_set -1 "user1"

7.多个zset取并集(同一用户的分数默认聚合函数为sum):zunionstore cus_order_set3 3 cus_order_set cus_order_set1 cus_order_set2 [aggregate SUM|MIN|MAX] [WEIGHTS weight1 weight2]

8.多个zset取交集:zinterstore(用法同zunionstore)

 

key过期时间监听:

1.修改redis.conf,设置notify-keyspace-events 为Ex

notify-keyspace-events 的参数可以是以下字符的任意组合, 它指定了服务器该发送哪些类型的通知:

字符发送的通知
K 键空间通知,所有通知以 __keyspace@<db>__ 为前缀
E 键事件通知,所有通知以 __keyevent@<db>__ 为前缀
g DEL 、 EXPIRE 、 RENAME 等类型无关的通用命令的通知
$ 字符串命令的通知
l 列表命令的通知
s 集合命令的通知
h 哈希命令的通知
z 有序集合命令的通知
x 过期事件:每当有过期键被删除时发送
e 驱逐(evict)事件:每当有键因为 maxmemory 政策而被删除时发送
A 参数 g$lshzxe 的别名

2.重启redis

3.监听配置类

package com.lbh360.order.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * @Description redis监听配置
 * @Author bofeng
 * @Date 2020/4/19 15:15
 * @Version 1.0
 */
@Configuration
public class RedisListenerConfig {
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }
}

4.监听器

package com.lbh360.order.callback;

import com.lbh360.order.model.response.OrderResp;
import com.lbh360.order.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description 待接单超时监听
 * @Author bofeng
 * @Date 2020/4/19 15:16
 * @Version 1.0
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    private static final Logger logger = LoggerFactory.getLogger(RedisKeyExpirationListener.class);

    @Resource
    private OrderService orderService;


    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        logger.info("onMessage, message:{}, pattern:{}", message, pattern);

        //失效的key
        String expiredKey = message.toString();
        String orderNo = expiredKey.substring(expiredKey.lastIndexOf(OrderResp.ASK_ORDER_PRE) + 1);
        //取消订单
        orderService.cancelOrder(orderNo);
    }
}

5.解决redis过期时间键乱码,在redis配置类加入以下方法

    /**
     * 解决redis过期时间乱码
     *
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        //一般我们序列化会采用String,object格式
        RedisTemplate<String, Object> Template = new RedisTemplate<>();
        Template.setConnectionFactory(factory);

        //json序列化格式
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(objectMapper);

        //String的序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        //key采用String格式序列化
        Template.setKeySerializer(stringRedisSerializer);
        //hash采用String格式序列化
        Template.setHashKeySerializer(stringRedisSerializer);
        //value采用jackson序列化
        Template.setValueSerializer(serializer);
        //hash的value采用jackson序列化
        Template.setHashValueSerializer(serializer);
        Template.afterPropertiesSet();
        return Template;
    }

 

四、jedis使用

1、单机版

@Test
    public void testJedisPool() throws Exception {
        // 第一步:创建一个JedisPool对象。需要指定服务端的ip及端口。
        JedisPool jedisPool = new JedisPool("192.168.25.128", 6379);
        // 第二步:从JedisPool中获得Jedis对象。
        Jedis jedis = jedisPool.getResource();
        // 第三步:使用Jedis操作redis服务器。
        jedis.set("jedis", "test");
        String result = jedis.get("jedis");
        System.out.println(result);
        // 第四步:操作完毕后关闭jedis对象,连接池回收资源。
        jedis.close();
        // 第五步:关闭JedisPool对象。
        jedisPool.close();
    }

2、集群版

@Test
    public void testJedisCluster() throws Exception {
        // 第一步:使用JedisCluster对象。需要一个Set<HostAndPort>参数。Redis节点的列表。
        Set<HostAndPort> nodes = new HashSet<>();
        nodes.add(new HostAndPort("192.168.25.128", 7001));
        nodes.add(new HostAndPort("192.168.25.128", 7002));
        nodes.add(new HostAndPort("192.168.25.128", 7003));
        nodes.add(new HostAndPort("192.168.25.128", 7004));
        nodes.add(new HostAndPort("192.168.25.128", 7005));
        nodes.add(new HostAndPort("192.168.25.128", 7006));
        JedisCluster jedisCluster = new JedisCluster(nodes);
        // 第二步:直接使用JedisCluster对象操作redis。在系统中单例存在。
        jedisCluster.set("hello", "100");
        String result = jedisCluster.get("hello");
        // 第三步:打印结果
        System.out.println(result);
        // 第四步:系统关闭前,关闭JedisCluster对象。
        jedisCluster.close();
    }

 

 

      

posted on 2018-12-23 23:38  bofeng  阅读(228)  评论(0编辑  收藏  举报