SpringBoot集成Redis

  1. 持久化

  2. 集群

  3. 事务


2、测试Redis

SpringBoot操作数据,Spring-Data、 jbdc、redis… …

SpringData与SpringBoot齐名的项目!

说明:在SpringBoot2.x之后,原来使用的jedis被替换为lettuce

jedis:采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,需使用jedis pool连接池!像BIO模式

lettuce:采用netty,实例可以再多个线程中进行共享,不存在线程不安全的情况!可以减少线程数据,更像NIO模式

img

新建一个项目

img

img

注意:

img

查看底层

img

源码分析:

@Bean

@ConditionalOnMissingBean( //如果未注入组件条件,我们自己可以定义一个redisTemplate来替换这个默认的

name = {“redisTemplate”}

)

public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {

//默认的 RedisTemplate 没有过多的设置 redis 都是需要序列化的 !

//两个泛型都是 Object Object的类型,我们往后使用需要强制转换<String,String>

RedisTemplate<Object, Object> template = new RedisTemplate();

template.setConnectionFactory(redisConnectionFactory);

return template;

}

@Bean

@ConditionalOnMissingBean //由于String 是redis 中最常用的类型 所有说单独提出来一个bean!

public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {

StringRedisTemplate template = new StringRedisTemplate();

template.setConnectionFactory(redisConnectionFactory);

return template;

}

1、导入依赖

2、配置连接

SpringBoot 所有的配置类 都有一个自动配置类 RedisAutoConfiguration

自动配置类都会绑定一个 properties 配置文件 RedisProperties

#配置 redis

spring.redis.host=127.0.0.1

spring.redis.port=6379

spring.redis

3、测试!

package com.kk;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.data.redis.connection.RedisConnection;

import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest

class Redis01SpringbootApplicationTests {

@Autowired

private RedisTemplate redisTemplate;

@Test

void contextLoads() {

/*

redisTemplate

opsForValue 操作字符串的 类似String

opsForList 操作List 类似List

opsForSet

opsForHash

opsForZSet

opsForGeo

opsForHyperLogLog

除了基本的操作 ,我们常用的方法都可以直接通过redisTemplate 比如事务和基本的CRUD

*/

//获取redis的连接对象

// RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();

// connection.flushDb();

// connection.flushAll();

redisTemplate.opsForValue().set(“kk1”,“kk2”);

System.out.println(redisTemplate.opsForValue().get(“kk1”));

}

}

img

3、自定义redisTemplate

首先先建一个实体类,测试

User类

package com.kk.pojo;

import lombok.AllArgsConstructor;

import lombok.Data;

import lombok.NoArgsConstructor;

import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值