This is the first day of my participation in the Gwen Challenge in November. Check out the event details: [The Last Gwen Challenge 2021] (juejin.cn/post/702364… “Juejin. Cn/post / 702364…” )

RedisTemplate is the most abstract client that Spring Data Redis provides to users. Users can perform various operations directly through RedisTemplate. The installation of Redis can be described in the article

Spring-data-redis function description

Client comparison
  • Jedis: Using direct connection, multi-threaded operation is not safe. Use if you want to avoid multi-threaded insecurityjedis poolConnection pool.BIOmodel
  • Lettuce:netty, instances can be shared among multiple threads, and there is no thread insecurity. You can reduce the number of threads.NIOmodel
Spring – data – redis function
  • Connection pooling is automatically managed, providing a highly encapsulatedRedisTemplateclass
  • The same type of operation is encapsulated asoperationinterface
    • ValueOperations: Simple K-V operation
    • SetOperations: Data operation of the set type
    • ZSetOperations: Indicates zset data operation
    • HashOperations: Operations on map data
    • ListOperations: Operations on data of type list
  • Provides for keyboundA handy manipulation API that encapsulates a given key with bound and then performs a series of operations without specifying the key “explicitly” again, i.eBoundKeyOperations
  • Encapsulate transaction operations with container control.
  • There are several alternative strategies for “serialization/deserialization” of data (RedisSerializer)

Start configuring Redis

Release notes
  • Maven: 3.5.4
  • java: jdk8
  • Springboot: at 2.0.5
  • Spring – data – redis: at 2.0.5
Adding Maven dependencies
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Copy the code
Add the configuration
spring:
  redis:
    # Redis server address
    host: localhost
    # Redis server password (default null)
    password: 
    # Redis server port
    port: 6379 
    Redis database index (default: 16 shards, default: 0)
    database: 8 
    Redis server connection timeout (ms)
    timeout: 5000 
Copy the code
Adding a Tool Class

Add operation tool class of Redis Hash structure, set cache method, query cache method

@Component
public class RedisUtils {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
     /**
     * HashGet
     *
     * @paramThe key key cannot be NULL *@paramItem items cannot be null *@returnValue * /
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
	
	
	/** * puts data into a hash table, or creates ** if none exists@paramThe key key *@paramItem item *@paramThe value value *@returnTrue Successful false failed */
    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; }}}Copy the code
test

Use Map to place test data and query for print

Map<String, Object> nameMap = new HashMap<>();
nameMap.put("name"."faker");
redisUtils.hset("key123"."1", JsonMapper.defaultMapper().toJson(nameMap));

String value = (String) redisUtils.hget("key123"."1");
Map<String, Object> map = JSON.parseObject(value,Map.class);
System.out.println(map);
Copy the code

Spring Redis configuration items

Configuration items The default value instructions
spring.redis.client-name Client name to be set on connections with CLIENT SETNAME.
spring.redis.cluster.max-redirects Maximum number of redirects to follow when executing commands across the cluster.
spring.redis.cluster.nodes Comma-separated list of “host:port” pairs to bootstrap from. This represents an “initial” list of cluster nodes and is required to have at least one entry.
spring.redis.database 0.0 Database index used by the connection factory.
spring.redis.host localhost Redis Server IP address
spring.redis.jedis.pool.max-active 8.0 The maximum number of active connections that can be allocated by the pool at the specified time; Setting a negative number means no limit.
spring.redis.jedis.pool.max-idle 8.0 Maximum number of “idle” connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.jedis.pool.max-wait -1ms Maximum amount of time a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.jedis.pool.min-idle 0.0 Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if both it and time between eviction runs are positive.
spring.redis.jedis.pool.time-between-eviction-runs Time between runs of the idle object evictor thread. When positive, the idle object evictor thread starts, otherwise no idle object eviction is performed.
spring.redis.lettuce.cluster.refresh.adaptive false Whether adaptive topology refreshing using all available refresh triggers should be used.
spring.redis.lettuce.cluster.refresh.period Cluster topology refresh period.
spring.redis.lettuce.pool.max-active 8.0 Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.lettuce.pool.max-idle 8.0 Maximum number of “idle” connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.lettuce.pool.max-wait -1ms Maximum amount of time a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.lettuce.pool.min-idle 0.0 Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if both it and time between eviction runs are positive.
spring.redis.lettuce.pool.time-between-eviction-runs Time between runs of the idle object evictor thread. When positive, the idle object evictor thread starts, otherwise no idle object eviction is performed.
spring.redis.lettuce.shutdown-timeout 100ms Turn off delay time.
spring.redis.password Login password of the Redis server.
spring.redis.port 6379.0 Redis Server port number
spring.redis.sentinel.master Redis server name.
spring.redis.sentinel.nodes Comma-separated list of “host:port” pairs.
spring.redis.sentinel.password Password for authenticating with sentinel(s).
spring.redis.ssl false Enable SSL when the value is false.
spring.redis.timeout Link expiration time.
spring.redis.url Link urls. Including host, port, and password. User are ignored, for example: redis:// User:[email protected]: 6379

summary

Springboot and Redis integration is very simple, using the spring-boot-starter-data-redis dependency, configure their own connection information, you can connect to Redis for simple operations.