0
点赞
收藏
分享

微信扫一扫

springboot 与 Redis整合


SpringBoot 操作数据:Spring-data jpa jdbc mongodb redis!
SpringData 也是和SpringBoot 齐名的项目!
说明:在SpringBoot2.X 之后,原来使用的jedis被替换成了lettuce
jedis: 采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用jedis pool 连接池,更新BIO模式
lettuce: 采用netty ,实例可以在多个线程中进行共享,不存在线程不安全的情况,可以减少线程数据,更想NIO模式

整合步骤

引入依赖

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

springboot 与 Redis整合_后端

@Bean
    @ConditionalOnMissingBean(
        name = {"redisTemplate"}
    )  
    我们可以自定义RedisTemplate
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
    // 使用默认的RedisTemplate 没有过多的设置,但是我们实际当中一般都需要进行序列化
    //<Object, Object> 需要强转 <String, Object>
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    // 由于String类型是Redis经常使用的类型所以这个地方单独写了一个StringRedisTemplate 
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

配置相关信息

springboot 与 Redis整合_spring_02


根据实际中进行配置既可

测试

*/
@RestController
public class HelloController {

    @Resource
    private RedisTemplate redisTemplate;
    @RequestMapping("hello")
    public String hell(){
        redisTemplate.opsForValue().set("javakey","ddd");
        Object javakey = redisTemplate.opsForValue().get("javakey");
        System.out.printf(javakey.toString());
        redisTemplate.opsForValue().set("中文","我也是中文");
        System.out.println(redisTemplate.opsForValue().get("中文").toString());
        return "hello";
    }
}


举报

相关推荐

0 条评论