How to operate redis in Java

I. Introduction

If you don’t know much about redis, you can read this article, which explains it in great detail! ! !

(6 messages) What is redis and how to use redis_Shi is Null’s blog-CSDN blog icon-default.png?t=M1L8https://blog.csdn.net/weixin_51418964/article/details/123097822

2. Download the Jedis jar package

1. What is Jedis?

Jedis is a java tool for operating redis database.

2. Download steps

1. Official website download link:

Maven Repository: redis.clients » jedis (mvnrepository.com) icon-default.png?t=M1L8https://mvnrepository.com/artifact/redis.clients/jedis 2. Find one with a relatively large download volume (you can also download the latest one and give it a try)!

 3. Click jar(540k) to start downloading

4. If it is a Maven project, it is more convenient to copy the code directly to pom.xml.

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

 3. Import the jar package into the idea project

1. Create a new utils folder and copy the jedis jar package into it

 2. Then right-click and click Add as Lbrary...

 3. Download the jar package of JedisPool

1. Why use JedisPool

First of all, if we generate a Jedis object every time we use the cache, this means that many socket connections will be established, causing uncontrollable use of system resources, and even causing strange errors to occur.

However, if you use the singleton mode, the thread-safe mode cannot meet the high concurrency requirements, and the non-thread-safe mode may cause time-related errors.

Therefore, in order to avoid these problems, the concept of pool JedisPool was introduced.

JedissPool is a thread-safe network connection pool. We can create and manage Jedis instances through JedisPool, which can effectively solve the above problems and achieve high performance of the system.

2. Download steps

1. Click the official website link to download

Pool – Download Apache Commons Pool icon-default.png?t=M1L8https://commons.apache.org/proper/commons-pool/download_pool.cgi 2. Click the download ending with bin.zip

 3. Unzip and copy the jar package to the project folder. The import method is the same as jedis.

 4. Test use

1. Open the redis server

2. Write test code

@Test
    public void Test(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(100);            //最大允许连接数
        config.setMaxIdle(10);           //最大空闲连接数
        // 设置Jedis连接池
        JedisPool jedisPool = new JedisPool(config,"localhost",6379);
        Jedis jedis = jedisPool.getResource();           //获取连接
        jedis.set("hello","wocao");                    // 设置数据
        System.out.println(jedis.get("hello"));       // 获取数据
        jedis.close();                                // 关闭资源
    }

3. Running results

If you can see the green check mark, it means there is no problem with the import! ! !

 4. How to use jedis more conveniently

1. First write a jedis.properties file

host=127.0.0.1
port=6379
maxTotal=50
maxIdle=10

 2. Write another JedisUtils toolkit

public class JedisUtils {
    private static JedisPool jedisPool;
    static {
        //创建Properties对象
        Properties properties = new Properties();
        //关联文件
        try {
            //读取配置文件
            properties.load(JedisUtils.class.getClassLoader().getResourceAsStream("jedis.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取数据,设置到JedisPoolConfig中
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle")));
        config.setMaxTotal(Integer.parseInt(properties.getProperty("maxTotal")));
        //初始化JedisPool
        jedisPool = new JedisPool(config,properties.getProperty("host"),Integer.parseInt(properties.getProperty("port")));
    }
    /**
     * 获取连接方法
     */
    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
}

3. Write Jedis connection pool test

@Test
    public void TestPool(){
        Jedis jedis = JedisUtils.getJedis();      // 使用Utils工具类获取连接
        jedis.set("hello","redisPool");
        System.out.println(jedis.get("hello"));
        jedis.close();
    }

4. Running results 

5. Get various data types

1. String type test

@Test
    public void Test1(){
        Jedis jedis = new Jedis("localhost",6379);              //获取连接,默认空参为localhost 6379
        jedis.set("username","zhangsan");                //操作
        String username = jedis.get("username");           //获取
        System.out.println(username);
        jedis.close();                       //关闭连接
        jedis.setex("activcode",20,"woqiao");           //设置一个20秒以后自动删除的key
    }

 2. Hash data structure test

@Test
public void Test2(){
        Jedis jedis = new Jedis();
        jedis.hset("user","name","lisi");
        jedis.hset("user","gender","男");
        jedis.hset("user","age","23");
        String name = jedis.hget("user", "name");
        System.out.println(name);
        Map<String, String> user = jedis.hgetAll("user");
        System.out.println(user);
        jedis.close();
}

3. List data structure test

@Test
    public void Test3(){
        Jedis jedis = new Jedis("localhost",6379);
        jedis.lpush("mylist","a","b","c");
        jedis.rpush("mylist","a","b","c");
        List<String> mylist = jedis.lrange("mylist", 0, -1);    //范围获取
        System.out.println(mylist);                     //[c, b, a, a, b, c]
        String mylist1 = jedis.lpop("mylist");
        System.out.println(mylist1);                      //c
        String mylist2 = jedis.rpop("mylist");
        System.out.println(mylist2);                     //c
        jedis.close();
    }

4. set data structure test

@Test
    public void Test4(){
        Jedis jedis = new Jedis();
        jedis.sadd("myset","apple","banana","cat");

        Set<String> myset = jedis.smembers("myset");
        System.out.println(myset);             //[banana, apple, cat]
        jedis.close();
    }

5. sortedset data structure test

@Test
    public void Test5(){
        Jedis jedis = new Jedis();
        jedis.zadd("mysortedset",3,"亚瑟");
        jedis.zadd("mysortedset",30,"后裔");
        jedis.zadd("mysortedset",55,"孙悟空");
        // sortedset 获取
        Set<String> mysortedset = jedis.zrange("mysortedset", 0, -1);
        System.out.println(mysortedset);             //[亚瑟, 后裔, 孙悟空]
        jedis.close();
    }
}

Guess you like

Origin blog.csdn.net/weixin_51418964/article/details/123168954