[Redis] spring boot integrates Redis and Redis.conf

SpringBoot operation data: Spring data JPA JDBC mongodb redis!

SpringData is also as famous as SpringBoot!

explain:
After spring boot 2. X, the original jedis is replaced by lettuce?

  • Jedis: direct connection and multi thread operation are unsafe. If you want to avoid unsafe, use jedis pool connection pool, which is more like BIO mode
  • lettuce: with netty, instances can be shared among multiple threads. There is no thread insecurity! Thread data can be reduced, more like NIO mode

Integration test

1. Create a new springboot project
2. Import dependency
3. Configure connections
4. Test

1. Create a new Springboot project


2. Import dependency

<!-- operation redis -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>



1.pring all configuration classes have an automatic configuration class RedisAutoConfiguration
2. The automatic configuration class will bind a properties configuration file RedisProperties
3. View the source code:





Source code analysis:
    // jedis.watch(result)
    try {
      multi.set("user1",result);
      multi.set("user2",result);
      int i = 1/0 ; // The code threw an exception transaction, and the execution failed!
      multi.exec(); // Execute transaction!
   } catch (Exception e) {
      multi.discard(); // Abandon transaction
      e.printStackTrace();
   } finally {
      System.out.println(jedis.get("user1"));
      System.out.println(jedis.get("user2"));
      jedis.close(); // Close connection
   }
 }
}
@Bean
@ConditionalOnMissingBean(name = "redisTemplate") // You can define a redisTemplate to replace the default one!
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory
redisConnectionFactory)
  throws UnknownHostException {
  // The default RedisTemplate does not have too many settings, and redis objects need to be serialized
  // Both generic types are object types. For later use, you need to cast < string, Object >
  RedisTemplate<Object, Object> template = new RedisTemplate<>();
  template.setConnectionFactory(redisConnectionFactory);
  return template;
}
@Bean
@ConditionalOnMissingBean  // Since String is the most commonly used type in redis, a bean is proposed separately
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory
redisConnectionFactory)
  throws UnknownHostException {
  StringRedisTemplate template = new StringRedisTemplate();
  template.setConnectionFactory(redisConnectionFactory);
  return template;
}

3. Configure connection (yml format is preferred)

Later, when deploying the service to the server, change the host to 127.0.0.1 and make it local.

4. Test

@SpringBootTest
class RedisSpringbootApplicationTests {
	@Autowired
	@Qualifier("redisTemplate") //Specify name
	private RedisTemplate redisTemplate;
	
	@Autowired
	private RedisUtil redisUtil; //Use redisUtil to write its own tool class
	@Test
	public void test1(){
		redisUtil.set("name","kuangshen");
		System.out.println(redisUtil.get("name"));
	}

	@Test
	void contextLoads() {
		// In enterprise development, 80% of the cases will not use this native way to write code!
		// RedisUtils......
		// redisTemplate operates on different data types, and the api and instructions are the same
		// opsForValue operation String is similar to String
		// The opsForList operation is similar to List
		// opsForSet
		// opsForHash
		// opsForZSet
		// opsForGeo
		// opsForHyperLogLog

		// In addition to basic operations, common methods can be operated directly through redisTemplate, such as transactions and basic CRUD
		//Get the connection object of redis (rarely used)
		RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
		connection.flushDb();
		connection.flushAll();
		redisTemplate.opsForValue().set("mykey","wanzi666");
		System.out.println(redisTemplate.opsForValue().get("mykey"));
	}

	@Test
	public void test() throws JsonProcessingException {
		// Real development generally uses json to pass objects
		User user = new User("wanzi",3);
//        String jsonUser = new ObjectMapper().writeValueAsString(user);
		redisTemplate.opsForValue().set("user",user);
		System.out.println(redisTemplate.opsForValue().get("user"));
	}
}


For object saving:

@Test
	public void test() throws JsonProcessingException {
		// Real development generally uses json to pass objects
		User user = new User("wanzi",3);
//        String jsonUser = new ObjectMapper().writeValueAsString(user);
		redisTemplate.opsForValue().set("user",user);
		System.out.println(redisTemplate.opsForValue().get("user"));
	}

Write your own redistemplet in the RedisConfig file

This is a fixed template, which can be used directly in enterprises!

@Configuration
public class RedisConfig {
    // You have defined a RedisTemplate
    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // For the convenience of our own development, we generally directly use < string, Object >
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);

        // Json serialization configuration
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // Serialization of String
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // The key is serialized by String
        template.setKeySerializer(stringRedisSerializer);
        // The key of hash is also serialized by String
        template.setHashKeySerializer(stringRedisSerializer);
        // value is serialized by jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // The value serialization method of hash is jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();

        return template;
    }
}
In real distribution or in the company, you can generally see that the company encapsulates RedisUtil itself
@Component
public final class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    // =============================common============================
    /**
     * Specify cache expiration time
     * @param key  key
     * @param time Time (seconds)
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Get expiration time according to key
     * @param key Key cannot be null
     * @return Time (seconds) returns 0, which means it is permanently valid
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }


    /**
     * Determine whether the key exists
     * @param key key
     * @return true Exists false does not exist
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * Delete cache
     * @param key One or more values can be passed
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
            }
        }
    }


    // ============================String=============================

    /**
     * Normal cache fetch
     * @param key key
     * @return value
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
    
    /**
     * Normal cache put
     * @param key   key
     * @param value value
     * @return true Success false failure
     */

    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * Normal cache put and set time
     * @param key   key
     * @param value value
     * @param time  Time (seconds) time must be greater than 0. If time is less than or equal to 0, the infinite period will be set
     * @return true Success false failure
     */

    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * Increasing
     * @param key   key
     * @param delta How many to add (greater than 0)
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("The increment factor must be greater than 0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }


    /**
     * Diminishing
     * @param key   key
     * @param delta How many to reduce (less than 0)
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("Decrement factor must be greater than 0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }


    // ================================Map=================================

    /**
     * HashGet
     * @param key  Key cannot be null
     * @param item Item cannot be null
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
    
    /**
     * Get all key values corresponding to hashKey
     * @param key key
     * @return Corresponding multiple key values
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }
    
    /**
     * HashSet
     * @param key key
     * @param map Corresponding to multiple key values
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * HashSet And set the time
     * @param key  key
     * @param map  Corresponding to multiple key values
     * @param time Time (seconds)
     * @return true Success false failure
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * Put data into a hash table. If it does not exist, it will be created
     *
     * @param key   key
     * @param item  term
     * @param value value
     * @return true Success false failure
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Put data into a hash table. If it does not exist, it will be created
     *
     * @param key   key
     * @param item  term
     * @param value value
     * @param time  Time (seconds): Note: if the existing hash table has time, the original time will be replaced here
     * @return true Success false failure
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * Delete values from hash table
     *
     * @param key  Key cannot be null
     * @param item Item can make multiple non null able
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }


    /**
     * Judge whether there is a value of this item in the hash table
     *
     * @param key  Key cannot be null
     * @param item Item cannot be null
     * @return true Exists false does not exist
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }


    /**
     * hash If increment does not exist, it will create one and return the added value
     *
     * @param key  key
     * @param item term
     * @param by   How many to add (greater than 0)
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }


    /**
     * hash Diminishing
     *
     * @param key  key
     * @param item term
     * @param by   To reduce (less than 0)
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }


    // ============================set=============================

    /**
     * Get all the values in the Set according to the key
     * @param key key
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * Query from a set according to value whether it exists
     *
     * @param key   key
     * @param value value
     * @return true Exists false does not exist
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * Put data into set cache
     *
     * @param key    key
     * @param values Values can be multiple
     * @return Number of successful
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * Put set data into cache
     *
     * @param key    key
     * @param time   Time (seconds)
     * @param values Values can be multiple
     * @return Number of successful
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * Gets the length of the set cache
     *
     * @param key key
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * Remove with value
     *
     * @param key    key
     * @param values Values can be multiple
     * @return Number of removed
     */

    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    // ===============================list=================================
    
    /**
     * Get the contents of the list cache
     *
     * @param key   key
     * @param start start
     * @param end   End 0 to - 1 represent all values
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * Gets the length of the list cache
     *
     * @param key key
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * Get the value in the list through the index
     *
     * @param key   key
     * @param index When index index > = 0, 0 header, 1 second element, and so on; When index < 0, - 1, footer, - 2, the penultimate element, and so on
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * Put list into cache
     *
     * @param key   key
     * @param value value
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * Put list into cache
     * @param key   key
     * @param value value
     * @param time  Time (seconds)
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * Put list into cache
     *
     * @param key   key
     * @param value value
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * Put list into cache
     *
     * @param key   key
     * @param value value
     * @param time  Time (seconds)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Modify a piece of data in the list according to the index
     *
     * @param key   key
     * @param index Indexes
     * @param value value
     * @return
     */

    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Remove N values as value
     *
     * @param key   key
     * @param count How many are removed
     * @param value value
     * @return Number of removed
     */

    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}

In fact, all redis operations are very simple for java developers. It is more important to understand the idea of redis and the use and action scenarios of each data structure!

Redis.conf details

When the local redis or server redis is started, it is started through the configuration file.
However, redis deployed by dockers on the server directly looks at this: Start Redis in Docker and enter Redis
At work, some small configurations can make you stand out!
Whether experts have it or not, you know.

Company

The configuration file unit is not case sensitive

contain

It's like learning Spring, improve and include

network

bind 0.0.0.0   # Bound ip, allowing external access
protected-mode yes # Protection mode
port 6379  # port settings

currency

daemonize yes  # Run as a daemon. The default is no. We need to turn it on as yes
pidfile /var/run/redis_6379.pid  # If we run in the background mode, we need to specify a pid file!

Log level:
# Specify the server verbosity level.
# This can be one of:
# debug (a lot of information, useful for development/testing) 
# verbose (many rarely useful info, but not a mess like the debug level)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
loglevel notice
logfile "" # File location name of the log
databases 16  # The default number of databases is 16
always-show-logo yes  # Always show LOGO

snapshot

Persistence: the number of operations performed within the specified time will be persisted to the file. rdb. aof
redis is an in memory database. If there is no persistence, the data will be powered off and lost!

# If at least one 1 key has been modified within 900s, we will perform the persistence operation
save 900 1
# If at least 10 key s are modified within 300s, we can perform persistence operation
save 300 10
# If at least 10000 key s are modified within 60s, we will perform persistence operation
save 60 10000
# After learning persistence, we will define this test ourselves!
stop-writes-on-bgsave-error yes  # If persistence fails, do you still need to continue working!
rdbcompression yes # Whether to compress rdb files requires some cpu resources!
rdbchecksum yes # Check and verify errors when saving rdb files!
dir ./  # Directory where rdb files are saved!

REPLICATION replication, followed by master-slave REPLICATION

SECURITY security
You can set the password of redis here. By default, there is no password
requirepass password

Set password by command:

127.0.0.1:6379> config get requirepass  # Get redis password
1) "requirepass"
2) ""
127.0.0.1:6379> config set requirepass "123456"  # Set redis password
OK
127.0.0.1:6379> config get requirepass  # It is found that all commands have no permission
(error) NOAUTH Authentication required.
127.0.0.1:6379> ping
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth 123456  # Login with password!
OK
127.0.0.1:6379> config get requirepass
1) "requirepass"
2) "123456"

Restrict CLIENTS

maxclients 10000  # Set the maximum number of clients that can connect to redis
maxmemory <bytes>  # redis configures the maximum memory capacity
maxmemory-policy noeviction  # Processing strategy after the memory reaches the upper limit

6 Two strategies:
  1,volatile-lru: Only for those with expiration time set key conduct LRU((default)
  2,allkeys-lru :  delete lru Algorithmic key 
  3,volatile-random: Random deletion is about to expire key 
  4,allkeys-random: Random deletion 
  5,volatile-ttl :  Delete expiring 
  6,noeviction :  Never expire, return error

APPEND ONLY mode = = = AOF configuration

appendonly no   # AOF mode is not enabled by default. RDB persistence is used by default. In most cases, RDB is fully sufficient!
appendfilename "appendonly.aof"  # The name of the persistent file
# appendfsync always  # Each modification will sync. Consumption performance
appendfsync everysec  # Execute sync once every second, and you may lose this 1s of data!
# appendfsync no    # Do not execute sync. At this time, the operating system synchronizes data by itself. The speed is the fastest!

The specific configuration is in Redis persistence.

Tags: Redis

Posted on Tue, 30 Nov 2021 00:16:32 -0500 by avvllvva