Wechat search: science and technology cat, get the first time update

This article source address: github.com/jonssonyan/…

You need to deploy a Redis beforehand to test the connection later. This article uses the Spring Data Redis framework to operate Redis

Introduction of depend on

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <! -- spring-boot redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <! -- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version> </dependency> <! -- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.1</version> </dependency> <! -- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2. 58</version> </dependency> <! -- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>
Copy the code

Spring Boot configuration file application.properties

# Redis server address
spring.redis.host=127.0.0.1
# Redis server connection port
spring.redis.port=6379
# Redis database index (default 0)
#spring.redis.database=
# Redis server connection username (default null)
#spring.redis.username=
# Redis server connection password (default null)
#spring.redis.password=
Connection timeout (ms)
spring.redis.timeout=0
Copy the code

Redis configuration file RedisConfig

@Configuration
@ConditionalOnClass(RedisService.class)
public class RedisConfig {
    private RedisTemplate<String, Object> redisTemplate;

    @Bean
    @ConditionalOnMissingBean
    public RedisService redisService(a) {
        return new RedisService(redisTemplate);
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // redis configuration
    // -----------------------------------------------------------------------------------------------------------------

    /** * key serializer */
    private final StringRedisSerializer keyRedisSerializer = new StringRedisSerializer();

    /** * value serializer */
    private final RedisFastJsonSerializer<Object> valueRedisSerializer = new RedisFastJsonSerializer<>(Object.class);

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        // RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        // RedisCacheConfiguration - Serialization of values
        RedisSerializationContext.SerializationPair<Object> serializationPair = RedisSerializationContext.SerializationPair.fromSerializer(valueRedisSerializer);
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(serializationPair);

        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        // Configure the connection factory
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // Value serializer -RedisFastJsonSerializer
        redisTemplate.setValueSerializer(valueRedisSerializer);
        redisTemplate.setHashValueSerializer(valueRedisSerializer);
        // key serializer -StringRedisSerializer
        redisTemplate.setKeySerializer(keyRedisSerializer);
        redisTemplate.setHashKeySerializer(keyRedisSerializer);

        returnredisTemplate; }}Copy the code

RedisFastJsonSerializer

RedisFastJsonSerializer is a custom serialization and deserialization tool that automatically serializes objects when setting values to Redis

public class RedisFastJsonSerializer<T> implements RedisSerializer<T> {
    / / the new GenericFastJson2JsonRedisSerializer add white name, prevent fastjson deserialization error
    static {
        ParserConfig.getGlobalInstance().addAccept("com.springboot");
    }

    private final Class<T> clazz;

    public RedisFastJsonSerializer(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (Objects.isNull(t)) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (Objects.isNull(bytes) || ArrayUtils.isEmpty(bytes)) {
            return null;
        }
        return JSON.parseObject(newString(bytes, StandardCharsets.UTF_8), clazz); }}Copy the code

RedisService

Encapsulate some common Redis methods

@Service
public class RedisService {

    private final RedisTemplate<String, Object> redisTemplate;

    public RedisService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /** * Description: set the value **@paramThe key cache {@link RedisKey}
     * @paramThe value value *@paramSeconds Validity period (seconds) *@returnT the value in the cache */
    public <T> T setValue(RedisKey key, T value, long seconds) {
        redisTemplate.opsForValue().set(key.of(), value, seconds, TimeUnit.SECONDS);
        return value;
    }

    private Object getValue(String key) {
        if(! Optional.ofNullable(redisTemplate.hasKey(key)).orElse(Boolean.FALSE)) {return null;
        }
        return redisTemplate.opsForValue().get(key);
    }

    /** * Description: Specifies the value **@paramThe key cache {@link RedisKey}
     * @paramClazz caches the class object * of the corresponding object@return T or null
     * @see RedisService#getValue(String)
     */
    public <T> T getValue(RedisKey key, Class<T> clazz) {
        return clazz.cast(getValue(key.of()));
    }

    /** * Description: delete **@paramThe key cache {@link RedisKey}
     * @return boolean
     */
    public boolean delete(RedisKey key) {
        return Optional.ofNullable(redisTemplate.delete(key.of())).orElse(false);
    }

    /** * Description: Extends the expiration time of the specified key **@param key     {@link RedisKey}
     * @paramSeconds Validity period (seconds) *@return boolean
     */
    public boolean expire(RedisKey key, long seconds) {
        return Optional.ofNullable(redisTemplate.expire(key.of(), seconds, TimeUnit.SECONDS)).orElse(false);
    }

    public class Files {

        private static final String CACHE_KEY_PREFIX = "file:";

        private static final String FIELD_FILE_NAME = "fileName";

        private static final String FIELD_FILE_CONTENT = "fileContent";

        /** * Details: read the file object into memory, get the byte array, and finally {@codeBase64} encoding. Use cache prefix + file name as cache key * *@paramFile (Required) File object */
        @SneakyThrows
        public void setFile(File file) {
            final HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();

            final String fileName = Objects.requireNonNull(file, "File cannot be empty.").getName();
            final String fileContent = new String(
                    Base64.getEncoder().encode(IOUtils.toByteArray(FileUtils.openInputStream(Objects.requireNonNull(file, "File objects cannot be empty")))),
                    StandardCharsets.UTF_8
            );

            final HashMap<String, String> map = new HashMap<>(2);
            map.put(FIELD_FILE_NAME, fileName);
            map.put(FIELD_FILE_CONTENT, fileContent);
            ops.putAll(CACHE_KEY_PREFIX + fileName, map);
        }

        /** * Description: get file **@paramFileName (Required) fileName *@returnJava.io.File File object */
        @SneakyThrows
        public File getFile(String fileName) {
            final HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();

            / / the cache Key
            final Map<Object, Object> entries = ops.entries(CACHE_KEY_PREFIX + Objects.requireNonNull(fileName, "File name cannot be empty"));
            if (MapUtils.isEmpty(entries)) {
                return null;
            }

            final String cachedFileName = MapUtils.getString(entries, FIELD_FILE_NAME);
            final String cachedFileContent = MapUtils.getString(entries, FIELD_FILE_CONTENT);

            final File file = new File(FileUtils.getTempDirectoryPath() + cachedFileName);
            try (
                    final FileOutputStream out = new FileOutputStream(file);
                    final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out)
            ) {
                bufferedOutputStream.write(Base64.getDecoder().decode(cachedFileContent));
            }
            return file;
        }

        /** * Description: Gets the file's byte array **@paramFileName (Required) fileName *@returnByte [] Specifies the byte array of the file */
        public byte[] getBytes(String fileName) {
            final HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();

            final Map<Object, Object> entries = ops.entries(CACHE_KEY_PREFIX + Objects.requireNonNull(fileName, "File name cannot be empty"));
            returnBase64.getDecoder().decode(MapUtils.getString(entries, FIELD_FILE_CONTENT)); }}}Copy the code

Entity class

User

@Data
public class User implements Serializable {
    private static final long serialVersionUID = -2961686750510451767L;
    private Long id;
    private String name;
    private Integer age;
}
Copy the code

RedisKey

@Data
@Builder
public class RedisKey {

    public static final String SEPARATOR = ".";

    /** * Redis key prefix */
    private String prefix;

    /** * the contents of Redis key */
    private String suffix;

    public String of(a) {
        return String.format("%s.%s", prefix, suffix); }}Copy the code

ResultVO

View class that returns a JSON object

@Data
public class ResultVO<T> {
    private Integer code;
    private String msg;
    private T data;

    public static ResultVO<Object> success(Object object) {
        ResultVO<Object> resultVO = new ResultVO<>();
        resultVO.setCode(1);
        resultVO.setMsg("Success");
        resultVO.setData(object);

        return resultVO;
    }

    public static ResultVO<Object> success(a) {
        return success(null);
    }

    public static ResultVO<Object> fail(Object object) {
        ResultVO<Object> resultVO = new ResultVO<>();
        resultVO.setCode(0);
        resultVO.setMsg("Failure");
        resultVO.setData(object);
        return resultVO;
    }

    public static ResultVO<Object> fail(a) {
        return fail(null); }}Copy the code

Controller

@RestController
public class Controller {
    @Autowired
    private RedisService redisService;

    @PostMapping("/redis/set")
    public ResultVO<Object> set(a) {
        User user = new User();
        user.setId(1L);
        user.setName("wang");
        user.setAge(22);
        redisService.setValue(RedisKey.builder().prefix("user").suffix("wang").build(), user, 10000L);
        return ResultVO.success(redisService.getValue(RedisKey.builder().prefix("user").suffix("wang").build(), user.getClass())); }}Copy the code

References

[1] Redis: redis.io/