Getting Started with the Redis application [tutorial / summary]

abstract

Because the project registered user to send a verification code, need to learn redis-memory database, and therefore spent some time in the afternoon preliminary study. This blog belongs to the nature of learning content summary of today redis. After watching before or after reading this post, you can ask yourself three questions: Redis is what (What), why use Redis / Redis what's the use? (Why), how to use Redis (How).

  • Redis Brief
  • Redis install and simple application
  • Jedis(Redis for Java)
  • JedisPool (Jedis database connection pool)
  • JedisUtil (Redis simple manipulation tool package)
    • jedis.properties
    • pulic static Jedis getJedis()
    • public static void close(Jedis jedis)
Note: JedisUtil design and all the code is not a blogger original, complete excerpt from the Department of Park blog blogger Roy-Xin Bowen Jedis connection pool

A brief Redis

Brief text excerpt from Baidu Encyclopedia .

  • Feature
    • Support network (remote)
    • Memory Based
    • Yes endurance of
    • Datejust
    • Key-Value database
    • Available in multiple languages

redis is a key-value storage system. And Memcached Similarly, it supports relatively more stored value type, comprising a string (string), List (list), SET (set), zset (sorted set - ordered set) and hash (hash type). These data types are supported push / pop, add / remove and on the intersection and union, and difference richer operation, and these operations are atomic. On this basis, redis support a variety of different ways of sorting. Like with memcached, in order to ensure efficiency, the data is cached in memory. Redis difference is periodically updated in the data written to disk or to modify the operation of writing additional log file, and on this basis realize the master-slave (master and slave) synchronization.

Redis is a key-value high-performance database. redis appears, to a large extent compensate for the lack of such memcached key / value store, it can play a very good complement to relational database in some situations. It provides Java, C / C ++, C #, PHP, JavaScript, Perl, Object-C, Python, Ruby, Erlang and other clients, very easy to use.

Redis supports master-slave synchronization. Data can be synchronized from the primary server to an arbitrary number from the server, the server may be associated with the primary server from another server. This allows the tree Redis single executable copy. Intentionally or unintentionally, can save the data write operation. Since the full implementation of the publish / subscribe mechanism, so that the database synchronization from a tree anywhere, can subscribe to a channel and receive the full message master server publishing record. Synchronization scalability and redundancy data useful for a read operation.

Two Redis install and simple application

  • step2: decompression that is installed
  • step3: Run the server
    • D: \ Program \ Redis \ redis-server.exe D: \ Program \ Redis \ redis.windows.conf # server running redis
  • step4.1: client invokes the Redis (application) storage / data acquisition [String key-based key-value pair]
    • D: \ Program \ Redis \ redis-cli.exe -h 127.0.0.1 -p 6379 # redis client calls service
>set myKey abc
OK
>get myKey
"abc"
  • step4.2: password problem
    • View current redis have not set a password :( The following display shows no password)
127.0.0.1:6379> config get requirepass
1) "requirepass"
2) ""
+ 设置密码(方式一)
127.0.0.1:6379> config set requirepass abcdefg
OK
    + 再次查看当前redis就提示需要密码:
127.0.0.1:6379> config get requirepass
(error) NOAUTH Authentication required.
+ 设置密码(方式二:永久)
    + 打开配置文件 : redis.conf(假定设置为123)
requirepass foobared
requirepass 123
    + 保存后重启redis即可
  • step4.3: Remote service invocation (password required)
    • D: \ Program \ Redis \ redis-cli.exe -h <host: 127.0.0.1> -p <port: 6379> -a <password: 123> # redis client calls service

三 Jedis(Redis for Java)

  • jedis是官方首选的java客户端开发包
  • Redis不仅是使用命令来操作,现在基本上主流的语言都有客户端支持,比如java、C、C#、C++、php、Node.js、Go等。
  • 在官方网站里列一些Java的客户端,有Jedis、Redisson、Jredis、JDBC-Redis、等其中官方推荐使用Jedis和Redisson。
  • 在企业中用的最多的就是Jedis,Jedis同样也是托管在github上
  • 项目地址:https://github.com/xetorthio/jedis
  • 下载jedis解压后得到jar包如下:java操作redis数据库API(Jedis)
  • 基本用法
//连接redis服务器,192.168.0.100:6379
String ip="192.168.0.100";
jedis = new Jedis(ip, 6379);
//权限认证
jedis.auth("password");
public class RedisTest {
    @Test
    public void jedisPropertiesTest(){
        Jedis jedis = JedisUtil.getJedis();
        Print.print("ss: " + jedis.get("ss"));//output: ss:2423235
        JedisUtil.close(jedis);
    }

    @Test// 基于字符串存储的基本测试
    public void baseTest(){
        Jedis jedis = new Jedis("127.0.0.1",6379);
        jedis.auth("123456");
        //设置数据
        jedis.set("zengtai","1125418540");
        jedis.set("wangchen","2153253568");
        jedis.close();//释放资源
        Print.print("保存数据完成");

        //获取数据
        Print.print("ss: " + jedis.get("ss"));//output: ss:2423235
        Print.print("xx: " + jedis.get("xx"));//output: xx:bhdjfsahsf
        jedis.close();//释放资源
        Print.print("获取数据完成");

        //删除数据
        jedis.del("xx");
        jedis.close();//释放资源
        Print.print("删除数据完成");
        Print.print("xx: " + jedis.get("wangchen"));//output: xx:null
    }

    @Test//数据结构测试(栈/队列)
    public void dataStructureTest(){
        Jedis jedis = new Jedis("127.0.0.1",6379);
        jedis.auth("123456");

        //设置数据
        jedis.lpush("charsList","E","D","C","B");//添加List:B(0) C(1) D(2) E(3)
        jedis.lpush("charsList","A");//往key对应list左侧插入一个元素
        jedis.rpush("charsList","F");//往key对应list左侧插入一个元素
        Print.print("rpop:"+jedis.rpop("charsList"));//output: rpop:F
        Print.print("lpop:"+jedis.lpop("charsList"));//output: lpop:A

        Print.print("charsList[0]:"+jedis.lindex("charsList",0));//output: charsList[0]:B
        Print.print("charsList[1]:"+jedis.lindex("charsList",1));//output: charsList[1]:C
        jedis.lset("charsList",0,"<X>");//修改key对应list指定下标index的元素
        Print.print("charsList[0]:"+jedis.lindex("charsList",0));//output: charsList[0]:<X>

        jedis.close();//释放资源
    }
}

四 JedisPool(Jedis数据库连接池)

+ [【推荐(JedisUtil/连接池JedisPool)】Jedis连接池](https://www.cnblogs.com/xinruyi/p/9391140.html)
//1 获得连接池配置对象,设置配置项
JedisPoolConfig config = new JedisPoolConfig();
// 1.1 最大连接数
config.setMaxTotal(30);
//1.2 最大空闲连接数
config.setMaxIdle(10);
//获得连接池
JedisPool jedisPool = new JedisPool(config, "localhost", 6379);

Jedis jedis = null;
try {
    //3.获得核心对象
    jedis = jedisPool.getResource();
    //4.设置数据
    jedis.set("name", "xinruyi");
    //5.获得数据
    String name = jedis.get("name");
    System.out.println(name);
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (jedis != null) {
        jedis.close();
    }
}

//虚拟机关闭时,释放pool资源
if(jedisPool!=null){
    jedisPool.close();
}

五 JedisUtil(Redis简易封装的操纵工具)

实现Redis操纵(JedisUtil类)所依赖的工具有:

  • Redis数据库服务
  • Jedis(Redis for Java - API)
    • jedis是官方首选的java客户端开发包
    • Redis不仅是使用命令来操作,现在基本上主流的语言都有客户端支持
      • 比如 java、C、C#、C++、php、Node.js、Go等
    • 在官方网站里列一些Java的客户端,有Jedis、Redisson、Jredis、JDBC-Redis等
      • 其中,官方推荐使用Jedis和Redisson
    • 在企业中用的最多的就是Jedis,Jedis同样也是托管在github上
    • 地址:https://github.com/xetorthio/jedis
    • 下载jedis解压后得到jar包如下:java操作redis数据库API(Jedis)
  • JedisPool(Jedis连接池)
  • ResourceBundle(读取属性配置文件jedis.properties)
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ResourceBundle;

public final class JedisUtil {
    private JedisUtil() {
    }

    private static JedisPool jedisPool;
    private static int maxtotal;
    private static int maxwaitmillis;
    private static String host;
    private static int port;
    private static int timeout;
    private static String auth;//密码

    /*读取 jedis.properties 配置文件*/
    static {
        ResourceBundle rb = ResourceBundle.getBundle("jedis");
        maxtotal = Integer.parseInt(rb.getString("maxtotal"));
        maxwaitmillis = Integer.parseInt(rb.getString("maxwaitmillis"));
        host = rb.getString("host");
        port = Integer.parseInt(rb.getString("port"));
        auth = rb.getString("auth");
        timeout = Integer.parseInt(rb.getString("timeout"));
    }

    /*创建连接池*/
    static {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxtotal);
        jedisPoolConfig.setMaxWaitMillis(maxwaitmillis);
        jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, auth);
    }

    /*获取jedis*/
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    /*关闭Jedis*/
    public static void close(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
}

jedis.properties [jedis(redis for java)连接池配置信息]

maxtotal=100
maxwaitmillis=3000
host=127.0.0.1
port=6379
auth=123456
timeout=1000

测试与示例

    @Test
    public void jedisPropertiesTest(){
        Jedis jedis = JedisUtil.getJedis();
        Print.print("aiqing: " + jedis.get("aiqing"));//output: aiqing:sdvwtrguyw32
        JedisUtil.close(jedis);//释放资源
    }

六 参考文献

Guess you like

Origin www.cnblogs.com/johnnyzen/p/11105406.html