spring-data-redis 整合springboot 2.1.3.RELEASE

版权声明:不要随便复制~~ 技术更新有些东西也会相应更新 https://blog.csdn.net/chuxin_mm/article/details/88788381

既然要整合框架,那么必不可少的要查询官方文档。

网上的文档,可以作为参考,但是千万不要直接用,除非标好了版本等信息 (且需要自己验证) 。

spring-data-redis官方文档:https://docs.spring.io/spring-data/redis/docs/2.1.5.RELEASE/reference/html/

不过这文档里面,也没写其他东西,没有实质性的作用;还是看看吧。

其他版本,可以根据这个网址,自己找。

1. 引入依赖

<!-- redis所需 (自带lettuce 5.1.4.RELEASE) lettuce是springboot2.x后连接redis推荐使用的客户端 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- lettuce pool 缓存连接池 -->
<!-- <commons-pool2.version>2.6.1</commons-pool2.version> -->
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-pool2</artifactId>
   <version>${commons-pool2.version}</version>
</dependency>

## 因为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<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> 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<Object> 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<String, Object>中的配置的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<String> cacheNames = new HashSet<>();
        cacheNames.add("timeGroup");
        cacheNames.add("user");
        cacheNames.add("UUser");

        // 对每个缓存空间应用不同的配置
        Map<String, RedisCacheConfiguration> 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;

/**
 * <p>
 * 充电订单 前端控制器
 * </p>
 *
 * @author wangqinmin
 * @since 2019-03-21
 */
@RestController
@RequestMapping("/redis")
@Slf4j
@Api("redis")
public class RedisController extends BaseController {

    @Autowired
    private RedisTemplate redisTemplate;
    //private RedisTemplate<String, Object> 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;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wangqinmin
 * @since 2019-03-21
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class UUserServiceImpl extends BaseServiceImpl<UUserMapper, UUser> implements UUserService {

    @Autowired
    private UUserMapper uUserMapper;

    /**
     * 修改缓存
     * <p>
     * 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);
    }

}

猜你喜欢

转载自blog.csdn.net/chuxin_mm/article/details/88788381