【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等等。
相关推荐
周某某~5 分钟前
四.抽象工厂模式
java·设计模式·抽象工厂模式
异常君32 分钟前
高并发数据写入场景下 MySQL 的性能瓶颈与替代方案
java·mysql·性能优化
烙印60136 分钟前
MyBatis原理剖析(二)
java·数据库·mybatis
你是狒狒吗39 分钟前
TM中,return new TransactionManagerImpl(raf, fc);为什么返回是new了一个新的实例
java·开发语言·数据库
懒羊羊大王呀41 分钟前
Ubuntu20.04中 Redis 的安装和配置
linux·redis
勤奋的知更鸟1 小时前
Java编程之组合模式
java·开发语言·设计模式·组合模式
千|寻1 小时前
【画江湖】langchain4j - Java1.8下spring boot集成ollama调用本地大模型之问道系列(第一问)
java·spring boot·后端·langchain
爱编程的喵1 小时前
深入理解JavaScript原型机制:从Java到JS的面向对象编程之路
java·前端·javascript
on the way 1231 小时前
行为型设计模式之Mediator(中介者)
java·设计模式·中介者模式
保持学习ing1 小时前
Spring注解开发
java·深度学习·spring·框架