SpringBoot整合Redis

2022/7/5 2:20:21

本文主要是介绍SpringBoot整合Redis,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

SpringBoot整合Redis的pom坐标

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

Application.yml配置Redis

spring:
  redis:
    port: 6379
    host: localhost
#端口6379 和主机地址 127.0.0.1

在Idea使用Redis前,注意先从安装路径启动Redis,详细方法见上一篇博客

Redis操作,单一的Key-Value

@SpringBootTest
class J14SpringBootRedisApplicationTests {
    @Resource  //使用AutoWired会爆红
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        ValueOperations ops = redisTemplate.opsForValue();
        ops.set("name", "Terry");
        ops.set("age", "18");
        Object name = ops.get("name");
        Object age = ops.get("age");
        System.out.println(name);
        System.out.println(age);
    }

}

Redsi操作,hash存储结构

@SpringBootTest
class J14SpringBootRedisApplicationTests {
    @Resource
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        HashOperations ops = redisTemplate.opsForHash();
        ops.put("user","name","Terry");
        ops.put("user","age","18");
        ops.put("user","gender","male");
        ops.put("user","hair","long");
        Object name = ops.get("user", "name");
        Object age = ops.get("user", "age");
        Object gender = ops.get("user", "gender");
        Object hair = ops.get("user", "hair");
        System.out.println(name);
        System.out.println(age);
        System.out.println(gender);
        System.out.println(hair);
    }
}

 



这篇关于SpringBoot整合Redis的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程