跳至主要內容

Redis初识

知识库集成配置缓存ReidsRedis大约 4 分钟

Redis 官网

Windows 安装

下载地址:https://github.com/microsoftarchive/redis/releases/open in new window

CentOS 安装

# gcc环境
yum install -y wget gcc-c++
# 下载并解压缩Redis源码压缩包
wget http://download.redis.io/releases/redis-5.0.4.tar.gz
mkdir -p ~/tools/ && tar -zxf redis-5.0.4.tar.gz -C ~/tools/
cd ~/tools/redis-5.0.4  && make
# 安装Redis,需要通过PREFIX指定安装路径
cd ~/tools/redis-5.0.4  && make install PREFIX=/usr/local/redis
mkdir -p /usr/local/redis/etc/ && cp -r /root/tools/redis-5.0.4/redis.conf /usr/local/redis/etc/
# 修改配置文件 `vi /usr/local/redis/bin/redis.conf`
# 将daemonize由no改为yes
sed -i "s/daemonize no/daemonize yes/g" /usr/local/redis/etc/redis.conf
# 是否开启保护模式,由yes该为no
sed -i "s/protected-mode yes/protected-mode no/g" /usr/local/redis/etc/redis.conf

# 启动redis服务
/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis.conf
# 查看redis监听端口
netstat -tanp|grep redis
# 后端启动的关闭方式
/usr/local/redis/bin/redis-cli shutdown
# 查看redis 版本
/usr/local/redis/bin/redis-server --version
/usr/local/redis/bin/redis-server -v

其他命令说明

  • redis-server :启动 redis 服务
  • redis-cli :进入 redis 命令客户端
  • redis-benchmark: 性能测试的工具
  • redis-check-aof : aof 文件进行检查的工具
  • redis-check-dump : rdb 文件进行检查的工具
  • redis-sentinel : 启动哨兵监控服务

Redis 客户端链接

# 默认端口:6379
redis-cli -h 127.0.0.1 -p 6379

Redis 开机自启

cat >> /usr/lib/systemd/system/redis.service << EOF
[Unit]
Description=Redis In-Memory Data Store
Documentation=https://redis.io/
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis.conf
ExecStop=/usr/local/redis/bin/redis-cli shutdown
ExecReload=/bin/kill -s HUP \$MAINPID
Restart=always

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload && systemctl enable redis && systemctl start redis && systemctl status redis

Java 客户端 Jedis

github 地址:https://github.com/xetorthio/jedisopen in new window

  • 添加依赖

    <dependencies>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
        <!-- 单元测试Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    <build>
        <plugins> <!-- 配置Maven的JDK编译级别 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
    
  • 单实例连接

    @Test
    public void testJedis() {
        //创建一个Jedis的连接
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        //执行redis命令
        jedis.set("mytest", "hello world, this is jedis client!");
        //从redis中取值
        String result = jedis.get("mytest");
        //打印结果
        System.out.println(result);
        //关闭连接
        jedis.close();
    }
    
  • 连接池连接

    @Test
    public void testJedisPool() {
        //创建一连接池对象
        JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
        //从连接池中获得连接
        Jedis jedis = jedisPool.getResource();
        String result = jedis.get("mytest") ;
        System.out.println(result);
        //关闭连接
        jedis.close();
        //关闭连接池
        jedisPool.close();
    }
    
  • 连接 redis 集群

    创建 JedisCluster 类连接 redis 集群。

    @Test
    public void testJedisCluster() throws Exception {
        //创建一连接,JedisCluster对象,在系统中是单例存在
        Set<HostAndPort> nodes = new HashSet<>();
        nodes.add(new HostAndPort("192.168.242.129", 7001));
        nodes.add(new HostAndPort("192.168.242.129", 7002));
        nodes.add(new HostAndPort("192.168.242.129", 7003));
        nodes.add(new HostAndPort("192.168.242.129", 7004));
        nodes.add(new HostAndPort("192.168.242.129", 7005));
        nodes.add(new HostAndPort("192.168.242.129", 7006));
        JedisCluster cluster = new JedisCluster(nodes);
        //执行JedisCluster对象中的方法,方法和redis一一对应。
        cluster.set("cluster-test", "my jedis cluster test");
        String result = cluster.get("cluster-test");
        System.out.println(result);
        //程序结束时需要关闭JedisCluster对象
        cluster.close();
    }
    
  • Jedis 整合 spring

    配置 spring 配置文件 applicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
        <!-- 连接池配置 -->
        <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
            <!-- 最大连接数 -->
            <property name="maxTotal" value="30" />
            <!-- 最大空闲连接数 -->
            <property name="maxIdle" value="10" />
            <!-- 每次释放连接的最大数目 -->
            <property name="numTestsPerEvictionRun" value="1024" />
            <!-- 释放连接的扫描间隔(毫秒) -->
            <property name="timeBetweenEvictionRunsMillis" value="30000" />
            <!-- 连接最小空闲时间 -->
            <property name="minEvictableIdleTimeMillis" value="1800000" />
            <!-- 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放 -->
            <property name="softMinEvictableIdleTimeMillis" value="10000" />
            <!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 -->
            <property name="maxWaitMillis" value="1500" />
            <!-- 在获取连接的时候检查有效性, 默认false -->
            <property name="testOnBorrow" value="true" />
            <!-- 在空闲时检查有效性, 默认false -->
            <property name="testWhileIdle" value="true" />
            <!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true -->
            <property name="blockWhenExhausted" value="false" />
        </bean>
    
        <!-- redis单机 通过连接池 -->
        <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="close">
            <constructor-arg name="poolConfig" ref="jedisPoolConfig" />
            <constructor-arg name="host" value="192.168.10.135" />
            <constructor-arg name="port" value="6379" />
        </bean>
    
        <!-- redis集群 -->
        <bean id="jedisCluster" class="redis.clients.jedis.JedisCluster">
            <constructor-arg index="0">
                <set>
                    <bean class="redis.clients.jedis.HostAndPort">
                        <constructor-arg index="0" value="192.168.10.135">
                        </constructor-arg>
                        <constructor-arg index="1" value="7001"></constructor-arg>
                    </bean>
                    <bean class="redis.clients.jedis.HostAndPort">
                        <constructor-arg index="0" value="192.168.10.135">
                        </constructorarg>
                        <constructor-arg index="1" value="7002"></constructor-arg>
                    </bean>
                    <bean class="redis.clients.jedis.HostAndPort">
                        <constructor-arg index="0" value="192.168.10.135">
                        </constructor-arg>
                        <constructor-arg index="1" value="7003"></constructor-arg>
                    </bean>
                    <bean class="redis.clients.jedis.HostAndPort">
                        <constructor-arg index="0" value="192.168.10.135">
                        </constructor-arg>
                        <constructor-arg index="1" value="7004"></constructor-arg>
                    </bean>
                    <bean class="redis.clients.jedis.HostAndPort">
                        <constructor-arg index="0" value="192.168.10.135">
                        </constructor-arg>
                        <constructor-arg index="1" value="7005"></constructor-arg>
                    </bean>
                </set>
            </constructor-arg>
            <constructor-arg index="1" ref="jedisPoolConfig"></constructor-arg>
        </bean>
    </beans>
    

    测试代码

    import javax.annotation.Resource;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisCluster;
    import redis.clients.jedis.JedisPool;
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:application.xml")
    public class TestJedis2 {
        @Autowired
        private JedisPool jedisPool;
        @Resource
        private JedisCluster cluster;
        @Test
        public void testJedisPool() {
            // 从连接池中获得连接
            Jedis jedis = jedisPool.getResource();
            String result = jedis.get("mytest");
            System.out.println(result);
            // 关闭连接
            jedis.close();
        }
        @Test
        public void testJedisCluster() throws Exception {
            // 执行JedisCluster对象中的方法,方法和redis一一对应。
            cluster.set("cluster-test", "my jedis cluster test");
            String result = cluster.get("cluster-test");
            System.out.println(result);
        }
    }