当前位置:网站首页>How to use jedis of redis

How to use jedis of redis

2022-07-05 03:46:00 Yisu cloud

Redis And Jedis How to use

This article mainly explains “Redis And Jedis How to use ”, The explanation in the text is simple and clear , Easy to learn and understand , Next, please follow Xiaobian's ideas and go deeper slowly , Study and learn together “Redis And Jedis How to use ” Well !

Redis And Jedis How to use

1.Jedis Introduction to

Jedis = Java + Redis

Redis Not only can you use commands to operate , Now the mainstream languages basically have API Support , such as Java、C#、C++、PHP、Node.js、Go etc. . List some on the official website Java The client of , Yes Jedis、Redisson、Jredis、JDBC-Redis It's officially recommended Jedis and Redisson.

Use Jedis operation redis Import required jar The package is as follows :

Redis And Jedis How to use

2.Jedis Basic operation

2.1Jedis Objects are commonly used API

notes : Each method is redis Command name in , The parameters of the method are the parameters of the command

Method

function

new Jedis(host, port)

establish Jedis The connection of , Parameters : Host name , Port number 6379

set(key,value)

Add the key and value of a string

get(key)

Get the value of the specified key

del(key)

Delete the specified key and value

hset(key,field,value)

Add one hash Type key - Field - value

hget(key,field)

adopt hash key - Field to get its value

lpush(key,values)

Add one from the left list Keys and elements of type

lpop(key)

Pop up an element from the left

rpop(key)

Pop an element from the right

close()

Close the connection

2.2Jedis Basic operation

Operation steps :

establish Jedis object , Appoint The server Address and port number

Write to the server

set String type data ,person= Zhang San

lpush add to list Data of type ,cities= zhuhai , Shenzhen , Guangzhou

Read the above data printout from the server

get Get the value of the string

lrange obtain list All the list elements

close Jedis object , Release resources

Check whether there is data in the database through the client

Console output :

Redis And Jedis How to use

In the database

Redis And Jedis How to use

Code :

package com.itheima.jedis;import redis.clients.jedis.Jedis;import java.util.List;/** *  Use Jedis towards redis Add string and list, Read their values  */public class Demo1 {    public static void main(String[] args) {        // establish Jedis Connection object         Jedis jedis = new Jedis("localhost", 6379);        // add to string type         jedis.set("person", " Zhang San ");        // add to list type         jedis.lpush("cities", " Guangzhou "," Shanghai "," dongguan ");        // Read string type         String person = jedis.get("person");        // Read list type         List<String> cities = jedis.lrange("cities", 0, -1);        // Output to the controller         System.out.println("person:" + person);        System.out.println("cities:" + cities);        // Close connection object         jedis.close();    }}

3.Jedis The use of connection pools

3.1Jedis The basic concept of connection pool

Redis And Jedis How to use

jedis The creation and destruction of connection resources consume a lot of program performance , therefore jedis For us jedis Connection pooling technology for ,jedis

The connection pool is initialized when it is created, and some connection objects are stored in the connection pool , Use jedis When connecting resources, you do not need to create your own jedis Yes

like , Instead, a resource is obtained from the connection pool for redis The operation of . After use , There is no need to destroy the jedis Connect resources ,

Instead, return the resource to the connection pool , For other requests .

3.2Jedis Connection pool API

JedisPoolConfig Configuration class

Functional specifications

JedisPoolConfig()

Create a configuration object , Use the parameterless construction method

void setMaxTotal()

Set the maximum number of connections in the connection pool

void setMaxWaitMillis()

Set the connection object Jedis The longest waiting time

JedisPool Connection pool class

explain

JedisPool( Configuration object , Server name , Port number )

Create connection pool

Parameters 1: The above configuration object , Parameters 2: Server name , Parameters 3:6379

Jedis getResource()

Get a from the connection pool Jedis Connection object

void close()

Connection pool closing method , Connection pooling is not normally closed

3.3JedisPool Basic use of

demand :

Use connection pooling to optimize jedis operation

Development steps

Create a connection pool configuration object , Set the maximum number of connections 10, Set the maximum waiting time for users 2000 millisecond

Use the configuration object as a parameter , Create connection pool object

Get from the connection pool jedis Connection object , perform redis command .

perform redis command sadd write in set Set type data :students= Bones jing , The Monkey King , Pig eight quit

perform redis command smembers Read the data in the collection

Output read data

Close connection object ( Usually, the connection pool is not closed )

Running effect

Redis And Jedis How to use

Execute code

package com.itheima.jedis;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;import java.util.Set;/** *  establish Jedis Connection pool  */public class Demo2 {    public static void main(String[] args) {        //1)	 Create a connection pool configuration object , Set the maximum number of connections 10, Set the maximum waiting time for users 2000 millisecond         JedisPoolConfig config = new JedisPoolConfig();        config.setMaxTotal(10);        config.setMaxWaitMillis(2000);        //2)	 Use the configuration object as a parameter , Create connection pool object         JedisPool pool = new JedisPool(config, "localhost", 6379);        //3)	 Get from the connection pool jedis Connection object , perform redis command .        Jedis jedis = pool.getResource();        //4)	 perform redis command sadd write in set Set type data :students= Bones jing , The Monkey King , Pig eight quit         jedis.sadd("students", " Bones jing ", " The Monkey King ", " Pig eight quit ");        //5)	 perform redis command smembers Read the data in the collection         Set<String> students = jedis.smembers("students");        //6)	 Output read data         System.out.println(students);        //7)	 Close connection object ( Usually, the connection pool is not closed )        jedis.close();        pool.close();    }}

4. Case study : To write jedis Connection pool tool class

4.1 The corresponding API Learning from

java.util.ResourceBundle Class is specifically used for : Read under the classpath Properties Class of configuration file

java.util.ResourceBundle class

function

static ResourceBundle getBundle(" Configuration base name ")

Create... Through your own static methods ResourceBundle object

Parameters : Put it in src Next .properties file . There is no need to write extension in the parameter , As long as there is a master name

String getString(" Key name ")

Get value by key

Case study : obtain druid.properties Medium url attribute

package com.itheima.jedis;import java.util.ResourceBundle;/** *  Read properties file  */public class Demo3 {    public static void main(String[] args) {        // Get the resource binding object         ResourceBundle bundle = ResourceBundle.getBundle("druid");        System.out.println(bundle.getString("url"));    }}

4.2 Implementation of connection pool tool class

demand :

Implement the connection pool tool class , Obtained through tool class Jedis Connection object , Configuration parameters are written in the properties file

Call the tool class , Yes Redis Database operation

Execution effect :

Redis And Jedis How to use

Implementation steps :

stay src Directory to create a connection pool tool class : jedis.properties

Create static member variables JedisPool object

In a static block of code , Read src Profile under , obtain ResourceBundle object

Get the above four parameters , among host It's a string type , Other parameters should be converted to integer type

Instantiate configuration object , Instantiate the connection pool object

Writing static methods getJedis() return Jedis object

establish hash object : key employee, Add field name :name, value :NewBoy; Field name : salary, value :3000

Use hgetall Read hash Object output

close jedis object

jedis.properties The configuration file

#  Host name host=localhost#  Port number port=6379#  maximum connection maxTotal=20#  The longest waiting time maxWaitMillis=3000

JedisUtils.java

package com.itheima.utils;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;import java.util.ResourceBundle;/** *  Connection pool tool class  */public class JedisUtils {    // Create a connection object     private static JedisPool pool;    static {        // Create the configuration object of the connection pool         JedisPoolConfig config = new JedisPoolConfig();        // Set the maximum number of connections and the maximum waiting time         ResourceBundle bundle = ResourceBundle.getBundle("jedis");        // Get the attribute value in the configuration file         String host = bundle.getString("host");        int port = Integer.parseInt(bundle.getString("port"));        int maxTotal = Integer.parseInt(bundle.getString("maxTotal"));        int maxWaitMillis = Integer.parseInt(bundle.getString("maxWaitMillis"));        // Set the parameters of the configuration object         config.setMaxTotal(maxTotal);        config.setMaxWaitMillis(maxWaitMillis);        // Create connection pool object         pool = new JedisPool(config, host, port);    }    /**     *  obtain redis Connection object      * @return     */    public static Jedis getJedis() {        return pool.getResource();    }}

Use tool class :

package com.itheima.jedis;import com.itheima.utils.JedisUtils;import redis.clients.jedis.Jedis;import java.util.Map;/** *  Use tool class  */public class Demo4 {    public static void main(String[] args) {        // From the tool class Jedis object         Jedis jedis = JedisUtils.getJedis();        // establish hash object : key employee, Add field name :name, value :NewBoy; Field name : salary, value :3000        jedis.hset("employee", "name","NewBoy");        jedis.hset("employee", "salary","3000");        // Use hgetall Read hash Object output         Map<String, String> employee = jedis.hgetAll("employee");        System.out.println(employee);        // close jedis object         jedis.close();    }}

Thank you for reading , That's all “Redis And Jedis How to use ” Content. , After learning this article , I'm sure you're right Redis And Jedis I have a deeper understanding of how to use this problem , The specific use needs to be verified by practice . This is billion speed cloud , Xiaobian will push you articles with more relevant knowledge points , Welcome to your attention !

原网站

版权声明
本文为[Yisu cloud]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050306264349.html