【Spring连载】使用Spring Data访问Redis(一)----快速指南

【Spring连载】使用Spring Data访问Redis(一)----快速指南

一、导入依赖

在pom.xml文件加入如下依赖就可以下载到spring data redis的jar包了:

xml 复制代码
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</dependency>

二、Hello World程序

首先,你需要设置一个正在运行的Redis服务器。Spring Data Redis 需要Redis 2.6或更高版本,并且Spring Data Redis集成了Lettuce和Jedis这两个流行的开源Java库。现在,你可以创建一个简单的Java应用程序,用于向Redis存储和读取值。创建要运行的主应用程序,示例如下:

java 复制代码
public class RedisApplication {

	private static final Log LOG = LogFactory.getLog(RedisApplication.class);

    public JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration =
                new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName("localhost");
        redisStandaloneConfiguration.setDatabase(0);
        redisStandaloneConfiguration.setPassword(RedisPassword.of("123456"));
        redisStandaloneConfiguration.setPort(6379);
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }

    public static void main(String[] args) {
        JedisConnectionFactory connectionFactory = new RedisApplication().jedisConnectionFactory();
        connectionFactory.afterPropertiesSet();

        RedisTemplate<String, String> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setDefaultSerializer(StringRedisSerializer.UTF_8);
        template.afterPropertiesSet();

        template.opsForValue().set("foo", "bar");

        LOG.info("Value at foo:" + template.opsForValue().get("foo"));

        connectionFactory.destroy();
    }
}

即使在这个简单的示例中,也有一些值得注意的事情需要指出:

  • 你可以使用RedisConnectionFactory创建RedisTemplate的实例(或ReactiveRedisTemplate,用于响应式使用)。连接工厂是在支持的驱动程序之上的抽象。
  • 没有单一的方法来使用Redis,因为它支持广泛的数据结构,如plain keys("strings"),lists, sets, sorted sets, streams, hashes等等。
相关推荐
echoyu.5 分钟前
java源代码、字节码、jvm、jit、aot的关系
java·开发语言·jvm·八股
彭于晏Yan1 小时前
IDEA如何进行远程Debug
java·ide
m0_748248021 小时前
Redis 简介与安装指南
数据库·redis·缓存
木木子99994 小时前
业务架构、应用架构、数据架构、技术架构
java·开发语言·架构
qq_5470261796 小时前
Flowable 工作流引擎
java·服务器·前端
鼓掌MVP7 小时前
Java框架的发展历程体现了软件工程思想的持续进化
java·spring·架构
编程爱好者熊浪8 小时前
两次连接池泄露的BUG
java·数据库
lllsure8 小时前
【Spring Cloud】Spring Cloud Config
java·spring·spring cloud
拽着尾巴的鱼儿8 小时前
fixed-bug:JPA 关联关系的对象序列化循环引用问题
spring·bug·jpa
鬼火儿8 小时前
SpringBoot】Spring Boot 项目的打包配置
java·后端