当前位置:网站首页>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 !
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 :
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 :
In the database
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
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
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 :
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 !
边栏推荐
- 【web审计-源码泄露】获取源码方法,利用工具
- glibc strlen 实现方式分析
- Basic function learning 02
- Mongodb common commands
- Google Chrome CSS will not update unless the cache is cleared - Google Chrome CSS doesn't update unless clear cache
- About authentication services (front and back, login, registration and exit, permission management)
- De debugging (set the main thread as hidden debugging to destroy the debugging Channel & debugger detection)
- The perfect car for successful people: BMW X7! Superior performance, excellent comfort and safety
- Clean up PHP session files
- speed or tempo in classical music
猜你喜欢
[wp][入门]刷弱类型题目
[luat-air105] 4.1 file system FS
DMX parameter exploration of grandma2 onpc 3.1.2.5
[untitled]
postman和postman interceptor的安装
The perfect car for successful people: BMW X7! Superior performance, excellent comfort and safety
Kbp206-asemi rectifier bridge kbp206
面试汇总:这是一份全面&详细的Android面试指南
JWT漏洞复现
Blue Bridge Cup single chip microcomputer -- PWM pulse width modulation
随机推荐
Share the newly released web application development framework based on blazor Technology
Share the newly released web application development framework based on blazor Technology
Basic knowledge of tuples
特殊版:SpreadJS v15.1 VS SpreadJS v15.0
Timing manager based on C #
Daily question 2 12
[2022 repair version] community scanning code into group activity code to drain the complete operation source code / connect the contract free payment interface / promote the normal binding of subordi
How to learn to get the embedding matrix e # yyds dry goods inventory #
It took two nights to get Wu Enda's machine learning course certificate from Stanford University
How to define a unified response object gracefully
【PHP特性-变量覆盖】函数的使用不当、配置不当、代码逻辑漏洞
[wp]bmzclub几道题的writeup
IPv6 experiment
error Couldn‘t find a package.json file in “你的路径“
花了2晚,拿到了吴恩达@斯坦福大学的机器学习课程证书
DMX parameter exploration of grandma2 onpc 3.1.2.5
speed or tempo in classical music
NEW:Devart dotConnect ADO.NET
Performance of calling delegates vs methods
postman和postman interceptor的安装