使用spring-boot-starter-data-redis访问redis入门示例(默认使用Lettuce)

本文介绍了如何在Spring Boot应用中使用spring-boot-starter-data-redis来接入Redis,详细讲解了引入依赖、配置Redis信息以及通过RedisTemplate进行数据操作的步骤。
摘要由CSDN通过智能技术生成

1、 引入依赖

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

需要注意:
官方默认使用的是Lettuce,不是Jedis。

可以看到spring-boot-starter-data-redis内部只引入了lettuce的依赖。
在这里插入图片描述
如果想要使用Jedis,在官方指南中有说明

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然,我可以为你提供一个Spring Boot Starter Data Redis的Demo。以下是一个简单的演示: 首先,确保你已经在你的项目中添加了`spring-boot-starter-data-redis`依赖。 接下来,创建一个Redis配置类,比如`RedisConfig`: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericToStringSerializer; @Configuration public class RedisConfig { @Bean public RedisConnectionFactory redisConnectionFactory() { return new LettuceConnectionFactory(); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory()); redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Object.class)); return redisTemplate; } } ``` 然后,创建一个简单的控制器类,比如`RedisController`: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class RedisController { private final RedisTemplate<String, Object> redisTemplate; @Autowired public RedisController(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } @GetMapping("/set/{key}/{value}") public void setValue(@PathVariable String key, @PathVariable String value) { redisTemplate.opsForValue().set(key, value); } @GetMapping("/get/{key}") public Object getValue(@PathVariable String key) { return redisTemplate.opsForValue().get(key); } } ``` 最后,启动你的Spring Boot应用程序,并通过以下URL进行测试: 设置值:`http://localhost:8080/set/{key}/{value}` 获取值:`http://localhost:8080/get/{key}` 请确保替换`{key}`和`{value}`为实际的键和值。 这只是一个简单的示例,你可以根据你的需求进一步扩展和定制。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值