详解Spring集成Redis的两种方式

 更新时间:2021年09月29日 08:53:37   作者:程序员阿牛  
在工作中,我们用到分布式缓存的时候,第一选择就是Redis,今天介绍一下SpringBoot如何集成Redis的,具有一定的参考价值,感兴趣的可以了解一下

在工作中,我们用到分布式缓存的时候,第一选择就是Redis,今天介绍一下SpringBoot如何集成Redis的,分别使用Jedis和Spring-data-redis两种方式。

一、使用Jedis方式集成

1、增加依赖

<!-- spring-boot-starter-web不是必须的,这里是为了测试-->
<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>redis.clients</groupId>
	<artifactId>jedis</artifactId>
</dependency>
<dependency>
<!-- fastjson不是必须的,这里是为了测试-->
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.73</version>
</dependency>

2、配置项

redis.host=localhost
redis.maxTotal=5
redis.maxIdle=5
redis.testOnBorrow=true
#以下方式也可以,SpringBoot同样能将其解析注入到JedisPoolConfig中
#redis.max-total=3
#redis.max-idle=3
#redis.test-on-borrow=true

3、配置连接池

/**
 * @author 公-众-号:程序员阿牛
 * 由于Jedis实例本身不非线程安全的,因此我们用JedisPool
 */
@Configuration
public class CommonConfig {
    @Bean
    @ConfigurationProperties("redis")
    public JedisPoolConfig jedisPoolConfig() {
        return new JedisPoolConfig();
    }

    @Bean(destroyMethod = "close")
    public JedisPool jedisPool(@Value("${redis.host}") String host) {
        return new JedisPool(jedisPoolConfig(), host);
    }
}

4、测试

/**
 * @author 公-众-号:程序员阿牛
 */
@RestController
public class JedisController {
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("getUser")
    public String getUserFromRedis(){
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId("A0001");
        userInfo.setUserName("张三丰");
        userInfo.setAddress("武当山");
        jedisPool.getResource().set("userInfo", JSON.toJSONString(userInfo));
        UserInfo userInfo1 = JSON.parseObject(jedisPool.getResource().get("userInfo"),UserInfo.class);
        return userInfo1.toString();
    }
}

运行结果如下:


我们可以自己包装一个RedisClient,来简化我们的操作

使用spring-data-redis

1、引入依赖

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

2、配置项

在application.properties中增加配置

spring.redis.host=localhost
spring.redis.port=6379

3、使用

/**
 * @author 公-众-号:程序员阿牛
 */
@RestController
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("getUser2")
    public String getUserFromRedis(){
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId("A0001");
        userInfo.setUserName("张三丰");
        userInfo.setAddress("武当山");
        redisTemplate.opsForValue().set("userInfo", userInfo);
        UserInfo userInfo1 = (UserInfo) redisTemplate.opsForValue().get("userInfo");
        return userInfo1.toString();
    }
}

是的,你只需要引入依赖、加入配置就可以使用Redis了,不要高兴的太早,这里面会有一些坑

4、可能会遇到的坑


使用工具查看我们刚才set的内容,发现key前面多了一串字符,value也是不可见的

原因

使用springdataredis,默认情况下是使用org.springframework.data.redis.serializer.JdkSerializationRedisSerializer这个类来做序列化
具体我们看一下RedisTemplate 代码如何实现的

/**
*在初始化的时候,默认的序列化类是JdkSerializationRedisSerializer
*/
public void afterPropertiesSet() {
        super.afterPropertiesSet();
        boolean defaultUsed = false;
        if (this.defaultSerializer == null) {
            this.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader != null ? this.classLoader : this.getClass().getClassLoader());
        }
   ...省略无关代码
}

如何解决

很简单,自己定义RedisTemplate并指定序列化类即可

/**
 * @author 公-众-号:程序员阿牛
 */
@Configuration
public class RedisConfig {
    @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;
    }

    @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;
    }

}/**
 * @author 公-众-号:程序员阿牛
 */
@Configuration
public class RedisConfig {
    @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;
    }

    @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;
    }
}

查看运行结果:

哨兵和集群

只需要改一下配置项即可

# 哨兵
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381

#集群
spring.redis.cluster.max-redirects=100
spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384

总结:

以上两种方式都可以,但是还是建议你使用Spring-data-redis,因为Spring经过多年的发展,尤其是Springboot的日渐成熟,已经为我们简化了很多操作。

到此这篇关于详解Spring集成Redis的两种方式的文章就介绍到这了,更多相关Spring集成Redis 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • springboot项目中controller层与前端的参数传递方式

    springboot项目中controller层与前端的参数传递方式

    这篇文章主要介绍了springboot项目中controller层与前端的参数传递方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • 深入学习java8 中的CompletableFuture

    深入学习java8 中的CompletableFuture

    本文主要介绍了java8中的CompletableFuture,CompletableFuture实现了CompletionStage接口和Future接口,前者是对后者的一个扩展,增加了异步回调、流式处理、多个Future组合处理的能力,使Java在处理多任务的协同工作时更加顺畅便利,下文需要的朋友可以参考一下
    2022-05-05
  • redis深入浅出分布式锁实现上篇

    redis深入浅出分布式锁实现上篇

    在单体应用中,如果我们对共享数据不进行加锁操作,会出现数据一致性问题,我们的解决办法通常是加锁。下面我们一起聊聊使用redis来实现分布式锁
    2022-08-08
  • 源码分析Spring 中 @Qualifier 注解基本用法

    源码分析Spring 中 @Qualifier 注解基本用法

    这篇文章主要介绍了源码分析Spring 中 @Qualifier 注解基本用法,在源码分析的过程中,也 GET 到 Spring 许多新的玩法,感兴趣的小伙伴赶紧去试试吧
    2023-08-08
  • 详解Spring Security如何在权限中使用通配符

    详解Spring Security如何在权限中使用通配符

    小伙伴们知道,在Shiro中,默认是支持权限通配符的。现在给用户授权的时候,可以一个权限一个权限的配置,也可以直接用通配符。本文将介绍Spring Security如何在权限中使用通配符,需要的可以参考一下
    2022-06-06
  • spring boot下 500 404 错误页面处理的方法

    spring boot下 500 404 错误页面处理的方法

    本篇文章主要介绍了spring boot下 500 404 错误页面处理的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-04-04
  • Java标识接口的使用方法

    Java标识接口的使用方法

    在本篇文章中小编给大家分享了关于Java标识接口的使用方法和教程内容,有需要的朋友们学习下。
    2019-01-01
  • Java小白第一次就能看懂的网络编程

    Java小白第一次就能看懂的网络编程

    网络编程是指编写运行在多个设备(计算机)的程序,这些设备都通过网络连接起来。本文介绍了一些网络编程基础的概念,并用Java来实现TCP和UDP的Socket的编程,来让读者更好的了解其原理
    2021-08-08
  • java实现写入并保存txt文件的代码详解

    java实现写入并保存txt文件的代码详解

    在本篇文章里小编给大家整理了关于java实现写入并保存txt文件的代码实例内容,需要的朋友们可以参考学习下。
    2020-02-02
  • JSP服务器端和前端出现乱码问题解决方案

    JSP服务器端和前端出现乱码问题解决方案

    这篇文章主要介绍了JSP服务器端和前端出现乱码问题解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02

最新评论