Spring-data-redis統合springboot 2.1.3.RELEASE

12503 ワード

フレームワークを統合する以上、公式ドキュメントを検索する必要があります.
ネット上のドキュメントは、参考にすることができますが、バージョンなどの情報が表示されていない限り、直接使用しないでください(自分で検証する必要があります).
Spring-data-redis公式ドキュメント:https://docs.spring.io/spring-data/redis/docs/2.1.5.RELEASE/reference/html/
しかし、このドキュメントには、他のものも書かれておらず、実質的な役割はありません.やはり見てみましょう.
他のバージョンは、このサイトに基づいて、自分で探すことができます.
 
1.導入依存


   org.springframework.boot
   spring-boot-starter-data-redis




   org.apache.commons
   commons-pool2
   ${commons-pool2.version}


##   springboot    ,  spring-data-redis        。
##    springboot    2.1.3.RELEASE ,   spring-data-redis   :2.1.5.RELEASE

2.配置を増やす(自分の状況に応じて配置する)
spring:
  redis:  ###### redis   
    host: 47.96.***.61  # ip  
    database: 0  # redis     0-15
    port: 63791  #    
    password: #      
    timeout: 30000s   #        (  1 )
    lettuce:
      shutdown-timeout: 100ms #           100ms
      pool: # lettuce    
        max-active: 8 #             8(-1 :      )
        max-wait: 60000ms #               -1ms (-1 :      )     1  
        max-idle: 8 #            8
        min-idle: 0 #            0

このときredisは簡単な呼び出しを開始することができます.
しかし、簡単な構成が必要です.例えばredisTempleteが保存したデータをシーケンス化したり、redisキャッシュの構成をしたり、
package com.toad.config.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
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.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author wangqinmin
 * @date: 2019/3/20 10:29
 * redis  : RedisConfig       
 *                @EnableCaching     
 */
@Configuration
@EnableCaching
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {

    /**
     *      redisTemplate
     *            :Lettuce,  RedisConnectionFactory        LettuceConnectionFactory
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setValueSerializer(jackson2JsonRedisSerializer());
        //  StringRedisSerializer         redis key 
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    /**
     * json   
     *
     * @return
     */
    @Bean
    public RedisSerializer jackson2JsonRedisSerializer() {
        //  Jackson2JsonRedisSerializer         redis value 
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
        return serializer;
    }

    /**
     *        
     *          RedisTemplate     key,value          
     *    RedisCacheConfiguration     。
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //         ,  config              
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //            ,    Duration   (     1  )
        config = config.entryTtl(Duration.ofMinutes(1))
                //    key string   
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                //   value json   
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))
                //      
                .disableCachingNullValues();

        //             set  
        Set cacheNames = new HashSet<>();
        cacheNames.add("timeGroup");
        cacheNames.add("user");
        cacheNames.add("UUser");

        //               
        Map configMap = new HashMap<>();
        configMap.put("timeGroup", config);
        //      ,    120 
        configMap.put("user", config.entryTtl(Duration.ofSeconds(120)));
        configMap.put("UUser", config.entryTtl(Duration.ofDays(3)));

        //                cacheManager
        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
                //                   ,         
                .initialCacheNames(cacheNames)
                .withInitialCacheConfigurations(configMap)
                .build();
        return cacheManager;
    }

}

redisの保存データ呼び出しの例:
package com.toad.swan.web.controller;

import com.toad.common.base.BaseController;
import com.toad.common.baseclass.ApiResult;
import com.toad.swan.entity.UUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 

* *

* * @author wangqinmin * @since 2019-03-21 */ @RestController @RequestMapping("/redis") @Slf4j @Api("redis") public class RedisController extends BaseController { @Autowired private RedisTemplate redisTemplate; //private RedisTemplate redisTemplate; /** * */ @PostMapping("/add") @ApiOperation(value = "redis ", notes = "redis", response = ApiResult.class) public Object addSysUser(@Valid @RequestBody UUser uUser) throws Exception { redisTemplate.opsForValue().set("uUserTest", uUser.toString()); logger.info("redis :[{}]", uUser.toString()); return success(true); } /** * */ @PostMapping("/get") @ApiOperation(value = "redis ", notes = "redis", response = ApiResult.class) public Object addUser() throws Exception { Object uu = redisTemplate.opsForValue().get("uUserTest"); redisTemplate.delete("uUserTest"); logger.info("redis :[{}]", uu); logger.error("redis :[{}]", uu); logger.warn("redis :[{}]", uu); logger.debug("redis :[{}]", uu); return success(uu); } }

redisキャッシュを使用する例:
package com.toad.swan.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.toad.swan.entity.UUser;
import com.toad.swan.mapper.UUserMapper;
import com.toad.swan.service.UUserService;
import com.toad.swan.web.param.UUserParam;
import com.toad.swan.web.vo.UUserVo;
import com.toad.common.baseclass.*;
import com.toad.common.base.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;

/**
 * 

* *

* * @author wangqinmin * @since 2019-03-21 */ @Service @Transactional(rollbackFor = Exception.class) @Slf4j public class UUserServiceImpl extends BaseServiceImpl implements UUserService { @Autowired private UUserMapper uUserMapper; /** * *

* redis -- ( ) * * @param uUser * @return * @CachePut , / , */ @CachePut(value = {"user"}, key = "#root.args[0]", unless = "#user eq null ") @Override public boolean redisCacheUpdateById(UUser uUser) { int i = uUserMapper.updateById(uUser); if (i == 1) { return true; } return false; } /** * * * @param id * @return * @CacheEvict , key condition unless , 。 * redis -- */ @CacheEvict(value = {"user"}, key = "#root.args[0]", condition = "#result eq true") @Override public boolean redisCacheRemoveById(String id) { int i = uUserMapper.deleteById(id); if (i == 1) { return true; } return false; } /** * redis -- * * @param id * @return * @Cacheable , , DB , key redis keyunless */ @Cacheable(value = "user", key = "args[0]", unless = "#result eq null ") @Override public UUserVo redisCacheGetUUserById(String id) { return uUserMapper.getUUserById(id); } }

package com.toad.common.base;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.toad.common.baseclass.OrderEnum;
import com.toad.common.baseclass.QueryParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wangqinmin
 * @date 2018-11-08
 */
public abstract class BaseServiceImpl, T> extends ServiceImpl implements BaseService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    protected Page setPageParam(QueryParam queryParam) {
        return setPageParam(queryParam, null, null);
    }

    protected Page setPageParam(QueryParam queryParam, String defaultOrderField, OrderEnum orderEnum) {
        Page page = new Page();
        page.setCurrent(queryParam.getCurrent());
        page.setSize(queryParam.getSize());
        page.setAsc(queryParam.getAscs());
        page.setDesc(queryParam.getDescs());

        if (orderEnum == OrderEnum.DESC) {
            page.setDesc(defaultOrderField);
        } else {
            page.setAsc(defaultOrderField);
        }

        return page;
    }

}
package com.toad.common.base;

import com.baomidou.mybatisplus.extension.service.IService;

/**
 * @author wangqinmin
 * @date 2018-11-08
 */
public interface BaseService extends IService {

}