Redis在CentOS 6.8中的安装方法,JAVA初级使用Redis连接池

阅读 69

2022-12-23


1、打开https://redis.io/在Download it下面直接点击“Redis 5.0.3 is the latest stable version.”下载redis-5.0.3.tar.gz然后传到centos系统

2、安装c++编译器(视网速快慢可能会等待很久)
# yum install gcc-c++
Is this ok [y/N]:y
Is this ok [y/N]:y

3、把redis-5.0.3.tar.gz复制到/usr/local/ 并开始编译→安装→启动redis
# mv /root/Downloads/redis-5.0.3.tar.gz /usr/local/
# cd /usr/local/
# tar -zxvf redis-5.0.3.tar.gz
# cd redis-5.0.3
# make
# make PREFIX=/usr/local/redis/ install
# cp redis.conf /usrl/local/redis
# cd /usr/local/redis/
# vim redis.conf

/daemonize
--把daemonize no 改成daemonize yes (这样才能让redis在后台运行,而不会因为命令行语句的输入导致中断redis线程)
/bind 127.0.0.1
--注释掉这一行#bind 127.0.0.1
/protected-mode yes
--把no改成no
:wq

[root#localhost redis]# ./bin/redis-cli shutdown
[root#localhost redis]# ./bin/redis-server ./redis.conf

4、查看redis是否运行
# ps -ef | grep -i redis

5、开启redis端口6379
# vim /etc/sysconfig/iptables
复制-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT这一行
然后把端口22改成6379(vim命令:复制当前行yy,粘贴p)
-A INPUT -m state --state NEW -m tcp -p tcp --dport 6379 -j ACCEPT
:wq
# service iptables restart

6、进入redis命令行
[root#localhost redis]# ./bin/redis-cli --raw
127.0.0.1:6379> set keyname keyvalue
127.0.0.1:6379> KEYS *
127.0.0.1:6379> get keyname
127.0.0.1:6379> del keyname

​​7、设置redis自动启动 javascript:void(0)​​

________________________

【JAVA连接、使用redis】
1、在POM.xml引入依赖包

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.0</version>
        </dependency>

2、测试代码

public class Test {

    public static void main(String[] args) {
        testRedis1();
        testRedis2();
    }

    public static void testRedis1() {
        Jedis jedis = new Jedis( "192.168.244.138", 6379 );//IP地址记得改成自己的
        jedis.set( "name", "舒工1" );
        String name = jedis.get( "name" );
        System.out.println( name );
        jedis.close();
    }

    public static void testRedis2() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal( 30 );
        config.setMaxIdle( 10 );
        JedisPool jedisPool = new JedisPool( config, "192.168.244.138", 6379 );//IP地址记得改成自己的
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set( "name", "舒工2" );
            String name = jedis.get( "name" );
            System.out.println( name );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) jedis.close();
            if (jedisPool != null) jedisPool.close();
        }
    }
}

精彩评论(0)

0 0 举报