redis integrates springboot's helloworld

Posted by frenchpl on Mon, 08 Jul 2019 18:57:32 +0200

Introducing dependencies

 compile 'org.springframework.boot:spring-boot-starter-data-redis'

There are two ways to use redis

1.Jedis

Jedis jedis = new Jedis("localhost");

2.RedisTemplate

@Autowired
private RedisTemplate redisTemplate;

To configure information in application.properties if using RedisTemplate, here I use Jedis relatively simply

Automatic configuration of redis

Under the application.properties file

#Automatic configuration of springboot for redis
# Redis database index (default 0)
spring.redis.database=0
# Redis Server Address
spring.redis.host=127.0.0.1
# Redis Server Connection Port
spring.redis.port=6379  
# Redis server connection password (blank by default)
spring.redis.password=
# Maximum number of connections in connection pool (use a negative value to indicate no limit)
spring.redis.pool.max-active=8  
# Maximum blocking wait time for connection pool (use a negative value to indicate no limit)
spring.redis.pool.max-wait=-1  
# Maximum idle connection in connection pool
spring.redis.pool.max-idle=8  
# Minimum idle connection in connection pool
spring.redis.pool.min-idle=0  
# Connection timeout (milliseconds)
spring.redis.timeout=0

Jedis uses

package com.test.booleanjava.helloRS.util;

import redis.clients.jedis.Jedis;

/**
 * @author booleanjava
 * Date: 2019/7/2 19:48
 * description:redis Tool class
 */
public class RedisUtil {
    static Jedis jedis = new Jedis("localhost");

    /**
     * Insert key and update if present
     * @param key
     * @param value
     * @return
     */
    public static   String set(String key, String value){
        return  jedis.set(key, value);
    }

    /**
     * Get the value of key
     * @param key
     * @return
     */
    public static String get(String key) {
        return jedis.get(key);
    }

    /**
     * Delete key
     * @param key
     * @return
     */
    public static Long del(String key){
        return jedis.del(key);
    }

    /**
     * Set a key (in seconds) with an expiration time
     * @param key
     * @param seconds
     * @param value
     * @return
     */
    public static String setex(final String key, final int seconds, final String value){
        return jedis.setex(key, seconds, value);
    }

    /**
     * Perform an operation if it does not exist, as a simple distributed lock
     *
     * @param key
     * @param value
     * @return true Represents execution, false indicates no execution
     */
    public static Boolean setnx(final String key, final String value){
        return jedis.setnx(key, value) == 1;
    }

}

RedisTemplates use

package com.test.booleanjava.helloRS.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author boolean
 * Date: 2019/7/2 19:48
 * description:
 */

@Component
public class Redisplus {

    @Autowired
    private  RedisTemplate redisTemplate;

    public  void set(String key, String value){
        redisTemplate.opsForValue().set(key, value);

    }
}

test

package com.test.booleanjava.helloRS.controller;


import com.test.booleanjava.helloRS.entity.User;
import com.test.booleanjava.helloRS.util.Redisplus;
import com.test.booleanjava.helloRS.service.IUserService;
import com.test.booleanjava.helloRS.util.RedisUtil;
import com.test.base.core.util.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author booleanjava
 * Date: 2019/7/2 19:48
 * description:
 */
@RestController
@RequestMapping("/helloRS/redisHello")
public class RedisHello {
    private final static Logger logger = LoggerFactory.getLogger(RedisHello.class);

    private final static String USERKEY = "com.test.booleanjava.helloRS.controller.setex";
    private final static String LOCKKEY = "com.test.booleanjava.helloRS.controller.lock";


    @Autowired
    private IUserService iUserService;

    @Autowired
    private Redisplus redisplus;

    @Autowired
    private RedisTemplate redisTemplate;
    RedisSerializer redisSerializer =new StringRedisSerializer();

    @RequestMapping("/hello")
    public String  hello(){
        LogUtil.info("redis Display of:[{}]", redisTemplate);
        return "hello, redis";
    }

    @RequestMapping("/set")
    public String  set(){
        Date date = new Date();
        redisTemplate.setKeySerializer(redisSerializer);
        redisTemplate.opsForValue().set("q", "1");
        redisTemplate.opsForValue().get("q");
        System.out.println(redisTemplate.opsForValue().get("q"));
        RedisUtil.set("a1", String.valueOf(1));
        logger.info("redis Display of:[{}]", redisTemplate);
        return "hello, set Once redis";
    }

    @RequestMapping("/setex")
    public String setex( ){
//        String key = "1min";
//        int seconds = 10;
//        String value = "Chen";
//        RedisUtil.setex(key, seconds, value);
//        String rs = RedisUtil.get(key);
//        logger.info("values obtained: [{}], rs);
        String value = RedisUtil.get(USERKEY);
        if (value != null) {
            logger.info("Cached user Value:[{}]", value);
            return value;
        }
        User user = iUserService.query().eq("name", "chen").one();
        logger.info("user Value of:[{}]",user.toString());
        if (user != null ) {
            RedisUtil.setex(USERKEY, 60, user.toString());
        }
        return "hello,booleanjava,Time-bound key";
    }

    @RequestMapping("/del")
    public String del(String key) {
        redisTemplate.delete(key);
        return "hello, del Once redis";
    }

    /**
     * Make a distribution lock,
     *Lock, write, and unlock
     * @return
     */
    @RequestMapping("/lock")
    public String lock() {
        //Locking
        RedisUtil.setnx(LOCKKEY,LOCKKEY);
        //Write business code, one person I get drunk

        //Unlock
        RedisUtil.del(LOCKKEY);

        return "hello, lock Once redis";
    }
}

Source code

https://github.com/blackdogss/HelloWorld/tree/master/helloRS

thorough

background

Most Internet companies usually use myslq as their database to store data, but mysql stores data at the expense of influencing IO, so mysql is a common bottleneck of the system. To solve this problem, redis, a non-relational database, appears, which is reasonable.Redis likes to operate in memory and is much more efficient than mysql at fiddling around on disk, so it's loved.

data structure

redis has five data structures

1.String string

2.Hash Hash

3.List List

4.Set Collection

5.Sorted Set

The most common type is the String type, which is often used as a cache to ease direct access to the database.Hash can be used as a user id, List can be used as a fan list, Set can be a mutual friend, Sorted Set can be a ranking.

Distributed Lock

Redis handles the examples listed above. Distributed locks are also possible. In a distributed system, interfaces face multiprocess and multithreaded access. If you rely on java locks, they will not solve the problem because there is no shared memory between processes. Using database locks is cumbersome, so redis is also needed to lock.How redis locks is mainly done with the setnx command, which sets the value if the key does not exist and does not exist. This feature is created for locks.

Public Number

Topics: PHP Redis Jedis Spring Database