当前位置:网站首页>20: Chapter 3: develop the pass service: 3: get through the redis server in the program; (it only connects with the redis server and does not involve specific business development)

20: Chapter 3: develop the pass service: 3: get through the redis server in the program; (it only connects with the redis server and does not involve specific business development)

2022-06-26 16:52:00 Small withered forest

explain :

(1) Points to note in this blog :

          ●  This blog is just to get through redis service ( Which is our program , Can operate redis The server ), Don't involve 【redis service , Specific application in the project 】, It doesn't involve 【 Specific business development 】;

          ●  I met a good one redis Graphic tool :rdm(Redis Desktop Manager) Tools , It feels good ;

          ● redis service , As a third party “ Tools ”, We wrote it in 【imooc-news-dev-common】 In general engineering ;

(2) of Redis The content of , If necessary, please refer to 【(13)Linux Basics 】、【(14)Redis】 The content of the column ;

Catalog

One : Our project , Why do you need it redis;

Two : install redis、redis brief introduction ;

3、 ... and : In the project , Integrate redis, Get through redis The server ;

1. stay 【imooc-news-dev-common】 In general engineering , introduce redis And so on ;

2. stay 【imooc-news-dev-common】 In general engineering , Create an operation redis Tool class of ;

3. stay 【imooc-news-dev-user】 This ( Actually need to use redis Of ) In the user microservice , stay application*.yml Configure... In the configuration file redis Service url、 Password and other information ;

4. stay 【imooc-news-dev-user】 This ( Actually need to use redis Of ) In the user microservice , stay HelloController in , Write code , To test “ Our program , Is it possible to connect redis”;

5. test ;


One : Our project , Why do you need it redis;

(1) After generating verification code , The verification code needs to be sent to the user ;;; The user inputs the received verification code in the front end , It will enter the back-end verification ;;; namely , On the back end , We need to store this native verification code ;;; and , For distributed microservice projects , We usually store them in redis in ( It will not be like that in single application , There is session in );


Two : install redis、redis brief introduction ;

If necessary, please refer to 【(13)Linux Basics 】、【(14)Redis】 The content of the column ;

meanwhile , stay 【Spring Boot E-commerce projects 31: Commodity classification module 10 : utilize Redis Cache accelerated response ;】 This Spring Boot In the project , Also used redis;

Here we are , Used in 【Redis Introduction 2 :Linux Installation under system Redis;】 in , Installed in the virtual machine created redis 了 ;

(1) Put the downloaded package , Upload to Linux System , It seems that FileZill Tools ;( I haven't used it myself , I use Xftp)

(2) Command line tools , You can also use SecureCRT;( I haven't used it myself , I use Xshell)

(3) have access to 【rdm(Redis Desktop Manager) Tools 】 This kind of redis Visualization tools , To aid development ;

          ● rdm Download and install , You can refer to 【Redis Desktop Manager(Redis Visualization tools ) Installation and usage guide 】;


3、 ... and : In the project , Integrate redis, Get through redis The server ;

1. stay 【imooc-news-dev-common】 In general engineering , introduce redis And so on ;

 <!--  introduce  redis  rely on  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <!--<version>2.1.5.RELEASE</version>-->
        </dependency>

        <!--okhttp rely on . Role is , Service to service rest request -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
        </dependency>

        <!-- jackson Three piece set  -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

        <!-- apache  Tool class 
        【commons-codec】 yes apache Code of the data provided / Decoding components , have access to 【Commons Codec】 To achieve MD5 Of ;
        【commons-lang3】 yes Apache One of the java.lang Enhanced version of package ,Lang3 by java.lang API There are many helper utilities available , In particular, string operation methods , Basic numerical methods , Object reflection , Concurrent , Create and serialize and system properties .
        【commons-fileupload】 Is a apache File upload component provided ;
        -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        </dependency>

        <!-- google  Tool class  -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>

        <!-- joda-time  Time tools , A time tool class  -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>

explain : 

(1) On these dependencies , If there is something unclear , You can refer to 【9: Chapter two : Architecture back end project :5:【 Polymerization Engineering 】 brief introduction ; Create top-level parent project ;】;

(2) Or that sentence , According to our distributed microservices project , each module Division of labor and relations ;;;edis service , As a third party “ Tools ”, We wrote it in 【imooc-news-dev-common】 In general engineering ;

2. stay 【imooc-news-dev-common】 In general engineering , Create an operation redis Tool class of ;

RedisOperator Tool class :

package com.imooc.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Title: Redis  Tool class 
 * @author  Between the wind shadow 
 */
@Component
public class RedisOperator {

    @Autowired
    private StringRedisTemplate redisTemplate;

    // Key( key ), ordinary key-value operation 

    /**
     *  Judge key Whether there is 
     * @param key
     * @return
     */
    public boolean keyIsExist(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     *  Implement the command :TTL key, In seconds , Return to a given  key The remaining lifetime of (TTL, time to live).
     *
     * @param key
     * @return
     */
    public long ttl(String key) {
        return redisTemplate.getExpire(key);
    }

    /**
     *  Implement the command :expire  Set expiration time , Unit second 
     *
     * @param key
     * @return
     */
    public void expire(String key, long timeout) {
        redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     *  Implement the command :increment key, increase key once 
     *
     * @param key
     * @return
     */
    public long increment(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     *  Implement the command :decrement key, Reduce key once 
     *
     * @param key
     * @return
     */
    public long decrement(String key, long delta) {
        return redisTemplate.opsForValue().decrement(key, delta);
    }

    /**
     *  Implement the command :KEYS pattern, Find all that match the given pattern  pattern Of  key
     */
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     *  Implement the command :DEL key, Delete one key
     *
     * @param key
     */
    public void del(String key) {
        redisTemplate.delete(key);
    }

    // String( character string )

    /**
     *  Implement the command :SET key value, Set up a key-value( String value  value Related to  key)
     *
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     *  Implement the command :SET key value EX seconds, Set up key-value And overtime ( second )
     *
     * @param key
     * @param value
     * @param timeout
     *            ( In seconds )
     */
    public void set(String key, String value, long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    /**
     *  If key non-existent , Is set , If there is , False report 
     * @param key
     * @param value
     */
    public void setnx60s(String key, String value) {
        redisTemplate.opsForValue().setIfAbsent(key, value, 60, TimeUnit.SECONDS);
    }

    /**
     *  If key non-existent , Is set , If there is , False report 
     * @param key
     * @param value
     */
    public void setnx(String key, String value) {
        redisTemplate.opsForValue().setIfAbsent(key, value);
    }

    /**
     *  Implement the command :GET key, return  key The string value associated .
     *
     * @param key
     * @return value
     */
    public String get(String key) {
        return (String)redisTemplate.opsForValue().get(key);
    }

    /**
     *  Batch query , Corresponding mget
     * @param keys
     * @return
     */
    public List<String> mget(List<String> keys) {
        return redisTemplate.opsForValue().multiGet(keys);
    }

    /**
     *  Batch query , The Conduit pipeline
     * @param keys
     * @return
     */
    public List<Object> batchGet(List<String> keys) {

//		nginx -> keepalive
//		redis -> pipeline

        List<Object> result = redisTemplate.executePipelined(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                StringRedisConnection src = (StringRedisConnection)connection;

                for (String k : keys) {
                    src.get(k);
                }
                return null;
            }
        });

        return result;
    }


    // Hash( Hashtable )

    /**
     *  Implement the command :HSET key field value, Hash table  key In the domain  field The value of the set  value
     *
     * @param key
     * @param field
     * @param value
     */
    public void hset(String key, String field, Object value) {
        redisTemplate.opsForHash().put(key, field, value);
    }

    /**
     *  Implement the command :HGET key field, Return hash table  key Given domain in  field Value 
     *
     * @param key
     * @param field
     * @return
     */
    public String hget(String key, String field) {
        return (String) redisTemplate.opsForHash().get(key, field);
    }

    /**
     *  Implement the command :HDEL key field [field ...], Delete hash table  key  One or more specified domains in , Domains that do not exist will be ignored .
     *
     * @param key
     * @param fields
     */
    public void hdel(String key, Object... fields) {
        redisTemplate.opsForHash().delete(key, fields);
    }

    /**
     *  Implement the command :HGETALL key, Return hash table  key in , All fields and values .
     *
     * @param key
     * @return
     */
    public Map<Object, Object> hgetall(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    // List( list )

    /**
     *  Implement the command :LPUSH key value, Put a value  value Insert into list  key The header 
     *
     * @param key
     * @param value
     * @return  perform  LPUSH After the command , The length of the list .
     */
    public long lpush(String key, String value) {
        return redisTemplate.opsForList().leftPush(key, value);
    }

    /**
     *  Implement the command :LPOP key, Remove and return to list  key The head element of .
     *
     * @param key
     * @return  list key The head element of .
     */
    public String lpop(String key) {
        return (String)redisTemplate.opsForList().leftPop(key);
    }

    /**
     *  Implement the command :RPUSH key value, Put a value  value Insert into list  key At the end of the watch ( Far right ).
     *
     * @param key
     * @param value
     * @return  perform  LPUSH After the command , The length of the list .
     */
    public long rpush(String key, String value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

}

explain :

(1) This tool class , I didn't write it ;; It defines many operations redis Methods ; You can have a rough look ;

(2) of java operation redis The content of , If necessary, please refer to 【(14)Redis】 The content of the column ;

3. stay 【imooc-news-dev-user】 This ( Actually need to use redis Of ) In the user microservice , stay application*.yml Configure... In the configuration file redis Service url、 Password and other information ;

4. stay 【imooc-news-dev-user】 This ( Actually need to use redis Of ) In the user microservice , stay HelloController in , Write code , To test “ Our program , Is it possible to connect redis”;

5. test ;

(1) First , The overall situation of the whole project install once ;

(2) then , start-up 【user】 The main startup class of ;

(3) then , visit 【user】 Of 【"/redis"】 Interface ;

thus , our redis Just fine , That is, our project can be connected to redis The server ;

原网站

版权声明
本文为[Small withered forest]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261638289755.html