Practical application of springboot+redis project

1. pom.xml in spring boot project reids tool class module

Add the jar dependency of redis

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <!-- Inherit the parent project of this project -->
    <parent>
        <artifactId>demo</artifactId>
        <groupId>com.lf</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <!-- Essential information -->
    <artifactId>demo-utils</artifactId>

    <dependencies>
        <!-- Introduce log4j2,Will introduce slf4j -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
        <!-- Use log4j2.yml This dependency must be added to the configuration file of the format to identify.yml -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.9.8</version>
        </dependency>
        <!-- Seven oxen -->
        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>7.2.18</version>
        </dependency>
        <!-- web Modular -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.0.6.RELEASE</version>
            <exclusions>
                <exclusion>
                    <!--
                       In creating Spring Boot During the project, we introduced spring-boot-starter,It contains spring-boot-starter-logging,
                       The dependent content is Spring Boot Default logging framework Logback,So we are introducing log4j Before that, you need to exclude the dependency of the package,
                       Reintroduction log4j Dependence
                       -->
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
        </dependency>
        
        **<!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.1.2.RELEASE</version>
        </dependency>**
        
        <!--poi-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.11-beta2</version>
        </dependency>
        <!--pinyin4j-->
        <dependency>
            <groupId>com.belerweb</groupId>
            <artifactId>pinyin4j</artifactId>
            <version>2.5.1</version>
        </dependency>
        <!--WeChat public address-->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-mp</artifactId>
            <version>3.4.0</version>
        </dependency>
    </dependencies>

</project>

2. Configure the redis parameter in application.yml

application.yml file

server:
  port: 81

spring:
  profiles:
   active: dev
   #active: prod
   
  jmx:
    enabled: false
    
logging:
  config: classpath:log4j2.yml
  
shiro:
  cookieName: demoWeb
  
redis:
  name: demo

application-dev.yml file

spring:
  redis:
    database: 0 	# Redis database index (default is0)
    host: localhost 	# Redis server address
    port: 6379	 	# Redis server connection port
    jedis:
      pool:
        max-idle: 8		#Connection pool maximum idle connections
        min-idle: 0		#Connection pool minimum free connection
        max-active: 8 	# Maximum number of connections in the connection pool (use a negative value to indicate no limit)
        max-wait: -1s	#Connection pool maximum blocking waiting time (negative value means no limit)
    timeout: 60s		#Connection timeout


  datasource:
    druid:
      primary:
        url: jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8&allowMultiQueries=true&useAffectedRows=true
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver
        initialSize: 5
        minIdle: 5
        maxActive: 20
      db2:
        url: 
        username: 
        password: 
        driver-class-name: 
        initialSize: 
        minIdle: 
        maxActive: 
shiro:
  topUrl: 127.0.0.1

url: 0.0.1:81
environment: dev
redis:
  name: demoDev

3. Redis configuration class

Redisconfig. Java class

package com.lf.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
		
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
		//Configure connection factory
        template.setConnectionFactory(factory);
		
		//Use Jackson2JsonRedisSerializer to serialize and deserialize the value value of redis (JDK is used by default)
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
		
        ObjectMapper om = new ObjectMapper();
		
		//Specify the domain to be serialized, field,get and set, and modifier range. ANY includes private and public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		
		//Specify the type of serialization input. The class must be non final decorated, such as String,Integer, etc., which will run out of exceptions
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		
        jackson2JsonRedisSerializer.setObjectMapper(om);
		
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key is serialized by StringRedisSerializer
        template.setKeySerializer(stringRedisSerializer);
		
        // The hash key also adopts the serialization method of StringRedisSerializer
        template.setHashKeySerializer(stringRedisSerializer);
		
        // value serialization is jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
		
        // value serialization of hash adopts jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
		
        template.afterPropertiesSet();
        return template;
    }
 /**
     * Data operation on hash type
     *
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * Data operation on redis string type
     *
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * Data operation on linked list type
     *
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * Data operations on unordered collection types
     *
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * Data operations on ordered collection types
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
    
}

4. Redis tool class

Redisutil. Java class

package com.lf.redis;

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

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

@Component
public class RedisUtil {

    @Value("${redis.name}")
    private String name;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * Specify cache expiration time
     *
     * @param key  key
     * @param time Time (seconds)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(name + ":" + 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 for permanent validity
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(name + ":" + key, TimeUnit.SECONDS);
    }

    /**
     * Determine whether the key exists
     *
     * @param key key
     * @return true Exist false do not exist
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(name + ":" + 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(name + ":" + key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(name + ":" + key));
            }
        }
    }

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

    /**
     * General cache access
     *
     * @param key key
     * @return value
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(name + ":" + 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(name + ":" + 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 should be greater than 0. If time is less than or equal to 0, 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(name + ":" + key, value, time, TimeUnit.SECONDS);
            } else {
                set(name + ":" + key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

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

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

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

    /**
     * HashGet
     *
     * @param key  Key cannot be null
     * @param item Item cannot be null
     * @return value
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(name + ":" + 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(name + ":" + key);
    }

    /**
     * HashSet
     *
     * @param key key
     * @param map Corresponding to multiple key values
     * @return true Success false failure
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(name + ":" + 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(name + ":" + key, map);
            if (time > 0) {
                expire(name + ":" + key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Put data into a hash table, and if it does not exist, create
     *
     * @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(name + ":" + key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Put data into a hash table, and if it does not exist, create
     *
     * @param key   key
     * @param item  term
     * @param value value
     * @param time  Time (seconds): 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(name + ":" + key, item, value);
            if (time > 0) {
                expire(name + ":" + key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Delete values in hash table
     *
     * @param key  Key cannot be null
     * @param item Item can make more than one cannot be null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(name + ":" + key, item);
    }

    /**
     * Determine 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 Yes, false, no
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(name + ":" + key, item);
    }

    /**
     * hash If increment does not exist, a new value will be created and returned
     *
     * @param key  key
     * @param item term
     * @param by   How many to add (greater than 0)
     * @return
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(name + ":" + key, item, by);
    }

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

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

    /**
     * Get all the values in the Set according to the key
     *
     * @param key key
     * @return
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(name + ":" + 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 Exist false do not exist
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(name + ":" + key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Put data into set cache
     *
     * @param key    key
     * @param values Values can be multiple
     * @return Success number
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(name + ":" + 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 Success number
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(name + ":" + key, values);
            if (time > 0) expire(name + ":" + key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

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

    /**
     * Remove the 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(name + ":" + 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 for all values
     * @return
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(name + ":" + key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

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

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

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

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

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

    /**
     * Put list in 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(name + ":" + key, value);
            if (time > 0) expire(name + ":" + 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(name + ":" + key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Remove N values as value
     *
     * @param key   key
     * @param count How many to remove
     * @param value value
     * @return Number of removed
     */
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(name + ":" + key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}

5. Entity class

Area.java

/**
 * Area table
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class Area implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * Primary key ID
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    /**
     * Area name
     */
    private String fullName;
    /**
     * Area abbreviation
     */
    private String shortName;
    /**
     * Position longitude
     */
    private String longitude;
    /**
     * Location latitude
     */
    private String latitude;
    /**
     * sort
     */
    private Integer sort;

Note: the class stored in redis must implement the serialization interface

6. Generate redis cache data

When querying the database, the acquired data is cached at the same time

/**
 * Region table service implementation class
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {
	@Autowired
    private RedisUtil redisUtil;
    
	/**
     * Generate cached data for all cities
     */
    public List<Area> createCityData() {
        QueryWrapper<Area> areaQueryWrapper = new QueryWrapper<>();
        areaQueryWrapper.lambda().eq(Area::getDeleteFlag, DeleteFlagEnum.Normal.getValue())
                					.orderByAsc(Area::getSort);
        List<Area> areaList = this.list(areaQueryWrapper);
        for(Area area: areaList){
        	redisUtil.hset("cityData", area.getId().toString(), area);
        }
        return areaList;
    }

}

7. Get redis cache data

@RestController
@RequestMapping(value = "/area")
public class AreaController extends BaseController {
 	@Autowired
    private RedisUtil redisUtil;
    
  	/**
     * Get city cache data
     */
    public Area getCityData(Integer cityId) {
        Area cityData = (Area) redisUtil.hget("cityData", cityId.toString());
        if (cityData == null) {
            cityData = areaService.getCityData(cityId);
        }
        return cityData;
    }
}

8, view

Download and install redis's image tool (RedisDesktopManager), and use RedisDesktopManager to check whether to generate cache.

Published 3 original articles, won praise 0, visited 156
Private letter follow

Tags: Redis Spring Java Maven

Posted on Sun, 02 Feb 2020 12:41:54 -0500 by psychosquirrel