Springboot集成redis(单机版or集群版)

方式1:集成spring缓存,使用注解的方式

方式2:使用jedis进行操作

集成单机版和集群版使用注解的方式一样,比较简单,在此只做一个示例

依赖

Springboot集成redis(单机版or集群版)

  • 单机版

配置文件

这里我使用的是bootstrap.yml作为项目的配置文件,如图

Springboot集成redis(单机版or集群版)

代码

Springboot集成redis(单机版or集群版)

单机版的比较简单,直接注入redisTemplate就行,走波测试?那必须的,如下图,这里用postman做测试,用过postman的都说好

Springboot集成redis(单机版or集群版)

然后用redis desktop manager查看一下是不是真的成功了

Springboot集成redis(单机版or集群版)

关于redistemplate其他操作,自行百度,目前有很多对它的操作进行封装的文章,

比如博主:https://www.cnblogs.com/superfj/p/9232482.html,接下来就看集群的吧

  • 集群版

配置文件

Springboot集成redis(单机版or集群版)

代码

/**
 * redis配置类
 **/
@Configuration
@ConditionalOnClass({JedisCluster.class})
public class RedisConfig {
    @Value("${spring.redis.cluster.nodes}")
    private String clusterNodes;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.lettuce.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.lettuce.pool.max-wait}")
    private long maxWaitMillis;
    @Value("${spring.redis.commandTimeout}")
    private int commandTimeout;
    @Bean
    public JedisCluster getJedisCluster() {
        String[] cNodes = clusterNodes.split(",");
        Set<HostAndPort> nodes = new HashSet<>();
        // 分割出集群节点
        for (String node : cNodes) {
            String[] hp = node.split(":");
            nodes.add(new HostAndPort(hp[0],Integer.parseInt(hp[1])));
        }
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        // 创建集群对象
//      JedisCluster jedisCluster = new JedisCluster(nodes,commandTimeout);
        return new JedisCluster(nodes,commandTimeout,jedisPoolConfig);
    }


    /**
     * 设置数据存入 redis 的序列化方式
     * </br>redisTemplate 序列化默认使用的jdkSerializeable, 存储二进制字节码, 导致key会出现乱码,所以自定义
     * 序列化类
     *
     * @param redisConnectionFactory
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

}

这就完了?对,这就完了,接下来测试

controller代码

Springboot集成redis(单机版or集群版)

service代码

Springboot集成redis(单机版or集群版)

serviceImpl代码

Springboot集成redis(单机版or集群版)

还是使用postman测试

Springboot集成redis(单机版or集群版)

不知道大家有没有好用的集群工具,我是找的好幸苦,因为我集群搭建的是主从,有两个节点都有这个数据

Springboot集成redis(单机版or集群版)

Ok,没毛病,继续看注解的

 

 

使用注解

使用集群和单机的配置都可以

说明:

        @Cacheable 表明Spring在调用方法之前,首先应该在缓存中查找方法的返回值。如果这个值能够找到,就会返回缓存的值。否则的话,这个方法就会被调用,返回值会放到缓存之中

        @cacheput 表明Spring应该将方法的返回值放到缓存中。在方法的调用前并不会 检查缓存,方法始终都会被调用

        @cacheevict 表明Spring应该在缓存中清除一个或多个条目

        @caching 这是一个分组的注解,能够同时应用多个其他的缓存注解

        @cacheconfig 可以在类层级配置一些共用的缓存配置

代码

 

启动类加个注解,开启缓存

Springboot集成redis(单机版or集群版)

然后贴一下配置类
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheing {

    @Bean
    public RedisTemplate<String, Object> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        //redis序列化器
        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);
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(jackson2JsonRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

写完了!老规矩,写方法测试

Controller层方法加个注解

Springboot集成redis(单机版or集群版)

这里就不贴数据存哪个库了,直接DeBug,预期,第一次进入方法会打印输出“进入方法”,第二次直接去缓存取,控制台什么都不会打印,测试走起

Springboot集成redis(单机版or集群版)

Springboot集成redis(单机版or集群版)

再请求一次

Springboot集成redis(单机版or集群版)

什么都没有打印,OK!完工!!!