SpringCloud+SpringBoot 项目搭建 (二) Redis

本篇文章接上一篇:SpringCloud+SpringBoot 项目搭建 (一) Eureka

SpringCloud+SpringBoot 项目搭建 (二) Redis

配置环境

	版本环境:
		redis:3.2.1

添加pom依赖

	<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
     </dependency>
	
	<dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>

配置文件properties

#redis 通用配置
spring.redis.database=7
spring.redis.lettuce.pool.max-wait=100000
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.max-active=100
spring.redis.timeout=5000

#redis集群配置
#spring.redis.cluster.nodes= localhost:6379,127.0.0.1:6379,192.168.1.7:6379
#spring.redis.cluster.max-redirects=3

#redis单机配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=dongyue

配置RedisConfig


@Configuration
@EnableAutoConfiguration
public class RedisConfig {

    @Bean
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //初始化一个RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        //设置CacheManager的值序列化方式为json序列化
        RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
        RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer);
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
        //设置默认超过时期是1天
        defaultCacheConfig.entryTtl(Duration.ofDays(1));
        //初始化RedisCacheManager
        return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
    }


    @Bean
    public StringRedisSerializer stringRedisSerializer() {
        return new StringRedisSerializer();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer<Object> 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);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setKeySerializer(stringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}

上面代码使用了jackson做序列化所以需要引入jackjson

 		<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>

简单封装redis

public interface RedisService {
    /**
     * Gets key.
     *
     * @param key the key
     *
     * @return the key
     */
    String getKey(String key);

    /**
     * Delete key.
     *
     * @param key the key
     */
    void deleteKey(String key);
    /**
     * Sets key.
     *
     * @param key   the key
     * @param value the value
     */
    void setKey(String key, String value);
    /**
     * Sets key.
     *
     * @param key     the key
     * @param value   the value
     * @param timeout the timeout
     * @param unit    the unit
     */
    void setKey(String key, String value, final long timeout, final TimeUnit unit);
}

@Slf4j
@Service
public class RedisServiceImpl implements RedisService {
    @Resource
    private StringRedisTemplate rt;
    @Override
    public String getKey(String key) {
        String value = null;
        ValueOperations<String, String> ops = rt.opsForValue();
        if (rt.hasKey(key)) {
            value = ops.get(key);
        }
        log.info("getKey. [OK] key={}, value={}", key, value);
        return value;
    }
    @Override
    public void deleteKey(String key) {
        rt.delete(key);
        log.info("deleteKey. [OK] key={}", key);
    }
    @Override
    public void setKey(String key, String value) {
        Preconditions.checkArgument(StringUtils.isNotEmpty(key), "Redis key is not null");
        ValueOperations<String, String> ops = rt.opsForValue();
        ops.set(key, value);
        rt.expire(key, GlobalConstant.REDIS_DEFAULT_EXPIRE, TimeUnit.MINUTES);
        log.info("setKey. [OK] key={}, value={}, expire=默认超时时间", key, value);
    }
    @Override
    public void setKey(String key, String value, long timeout, TimeUnit unit) {
        Preconditions.checkArgument(StringUtils.isNotEmpty(key), "Redis key is not null");
        Preconditions.checkArgument(unit != null, "TimeUnit is not null");
        ValueOperations<String, String> ops = rt.opsForValue();
        ops.set(key, value);
        rt.expire(key, timeout, unit);
        log.info("setKey. [OK] key={}, value={}, timeout={}, unit={}", key, value, timeout, unit);
    }
}

测试效果
在这里插入图片描述
在这里插入图片描述
项目目录:
在这里插入图片描述
至此redis集成完毕
下一篇:SpringCloud+SpringBoot 项目搭建 (三) MyBatis-Push

posted @ 2021-04-10 16:40  rr完美'诺言  阅读(21)  评论(0编辑  收藏  举报  来源