Spring Boot—— 整合Redis增删改查(极简)

       在传统的 SSM 中,需要开发者自己来配置 Spring Data Redis ,这个配置比较繁琐,主要配置 3 个东西:连接池、连接器信息以及 key 和 value 的序列化方案。

在 Spring Boot 中,经过Spring Boot的整合封装与自动化配置,在Spring Boot中整合Redis已经变得非常容易了,开发者只需要引入Spring Data Redis依赖,然后简单配下redis的基本信息,系统就会提供一个RedisTemplate供开发者使用。默认集成的 Redis 就是 Spring Data Redis,默认底层的连接池使用了 lettuce ,开发者可以自行修改为自己的熟悉的,例如 Jedis,只需修改依赖即可。

在Spring Boot 2.1.5之后包括2.1.5,远程访问Redis必须引入Spring security。

创建工程

1、首先去redis根目录打开Redis,如下:
[root@localhost redis-4.0.6]# redis-server redis.conf

2、接着输入密码,并清空:

[root@localhost redis-4.0.6]# redis-cli -a 123456 //输入密码
127.0.0.1:6379> ping
PONG  
127.0.0.1:6379> keys *      
1) "name"
127.0.0.1:6379> FLUSHALL   //清空
OK
127.0.0.1:6379> KEYS *
(empty list or set)
127.0.0.1:6379> 

3、创建工程,引入 Redis 依赖:

 最终完整的 pom.xml 依赖如下,默认底层的连接池使用了 lettuce:

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

配置 Redis 信息

在application.properties文件中配置Redis 的基本信息和连接池信息。

spring.redis.host=192.168.1.132
spring.redis.database=0
spring.redis.password=123456
spring.redis.port=6379
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0

spring.redis.lettuce.pool.min-idle=5
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=1ms
spring.redis.lettuce.shutdown-timeout=100ms

自动配置

当开发者在项目中引入了 Spring Data Redis ,并且配置了 Redis 的基本信息,此时,自动化配置就会生效。

我们从 Spring Boot 中 Redis 的自动化配置类中就可以看出:

@Configuration
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
    public RedisAutoConfiguration() {
    }

    @Bean
    @ConditionalOnMissingBean(
        name = {"redisTemplate"}
    )
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}
  1. 首先标记这个是一个配置类,同时该配置在 RedisOperations 存在的情况下才会生效(即项目中引入了 Spring Data Redis)
  2. 然后导入在 application.properties 中配置的属性
  3. 然后再导入连接池信息(如果存在的话)
  4. 最后,提供了两个 Bean ,RedisTemplate 和 StringRedisTemplate ,其中 StringRedisTemplate 是 RedisTemplate 的子类,两个的方法基本一致,不同之处主要体现在操作的数据类型不同,RedisTemplate 中的两个泛型都是 Object ,意味者存储的 key 和 value 都可以是一个对象,而 StringRedisTemplate 的 两个泛型都是 String ,意味者 StringRedisTemplate 的 key 和 value 都只能是字符串。如果开发者没有提供相关的 Bean ,这两个配置就会生效,否则不会生效。

测试使用

 创建测试Controller:

@RestController
public class HelloController {

    @Autowired  //注入
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("/set")
    public void set(){
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set("name","Hello World!");
    }
    @GetMapping("/get")
    public void get(){
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        System.out.println(ops.get("name"));
    }
}

然后启动项目,由于项目引入了Spring security, 所有接口已经被保护起来了,此时访问 localhost:8080/set 接口,会跳转至一个登录窗口,如下图:

这里的用户名默认是user,密码是是此时控制台打印的如下图,粘贴过来即可:

登陆成功后,我们来看一下Redis,如下:

然后继续访问localhost:8080/get 接口,控制台会打印出get到的值,如下:

好了,现在测试OK,试一下CRUD.

增删改查

1.首先编写Redis操作工具类。

package com.example.springboot.redis;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
 
/**
 * redis操作工具类
 * 基于RedisTemplate
 */
@Component
public class RedisUtils {
 
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
 
	/**
	 * 读取缓存
	 * 
	 * @param key
	 * @return
	 */
	public String get(final String key) {
		return redisTemplate.opsForValue().get(key);
	}
 
	/**
	 * 写入缓存
	 */
	public boolean set(final String key, String value) {
		boolean result = false;
		try {
			redisTemplate.opsForValue().set(key, value);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
 
	/**
	 * 更新缓存
	 */
	public boolean getAndSet(final String key, String value) {
		boolean result = false;
		try {
			redisTemplate.opsForValue().getAndSet(key, value);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
 
	/**
	 * 删除缓存
	 */
	public boolean delete(final String key) {
		boolean result = false;
		try {
			redisTemplate.delete(key);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}

2.然后就可以直接在service中通过RedisTemplate操作redis,使用redis进行缓存数据库查询。

 @Autowired   //注入刚才的工具类
 RedisUtils redisUtils;

/**
 * 查询
 * @param id
 * @return
 */
  public List<Menu> getAllMenus(){
        // 从redis缓存中提取数据
        String allMenus = redisUtils.get("AllMenus");
        // 如果没有,则从数据库中查询并放入缓存中
        if(allMenus == null) {
            redisUtils.set("AllMenus", String.valueOf(menuMapper.getAllMenus()));
        }
        return menuMapper.getAllMenus();
    }

/**
 * 修改
 *
 * @param article
 */
public void update(Article article) {
	// 删除redis中的缓存
	redisUtils.delete("article_" + article.getId());
	// 修改操作
	articleMapper.save(article);
}

/**
 * 删除
 *
 * @param id
 */
public void deleteById(String id) {
	// 删除redis缓存数据
	redisUtils.delete("article_" + id);
	// 删除操作
	articleMapper.deleteById(id);
}

完了,就这么简单,快去试试吧!

另外,还可以通过Spring Cache的形式来操作Redis,具体请移步至:Spring Boot中,Spring Cache + Redis

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李多肉同学

长得好看的人一般都喜欢发红包

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值