SpringBoot整合Redis

1.添加Redis的起步依赖

<!-- 因为要使用JSON,额外导入web的起步依赖,其中包含了JSON -->
<!-- web功能的起步依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 配置使用redis启动器 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.启动Redis服务器

在这里插入图片描述

3. 在SpringBoot配置文件中配置redis的连接信息

# Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379

4.创建实体Bean

package com.atlantis.domain;

public class User {
    private Integer id;
    private String username;
    private String password;

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }
    
	//省略getter、setter和toString方法 .. ..
}

5.注入RedisTemplate测试Redis操作

package com.atlantis;

import com.atlantis.domain.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = StartSpringBootApplication.class)
public class RedisTest {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void test() throws JsonProcessingException {
        // 从Redis缓存中获得指定的数据
        String userListData = redisTemplate.boundValueOps("user.findAll").get();
        // 如果Redis中没有数据
        if (null == userListData) {
            // 模拟从数据库获取数据
            List<User> users = new ArrayList<>();
            users.add(new User(1, "Atlantis", "123"));
            users.add(new User(2, "Olivia", "123"));
            // 转换成JSON格式字符串
            ObjectMapper om = new ObjectMapper();
            userListData = om.writeValueAsString(users);
            // 将数据存储到redis中,下次在查询直接从redis中获得数据,不用在查询数据库
            redisTemplate.boundValueOps("user.findAll").set(userListData);
            System.out.println("从数据库获得数据==================");
        } else {
            System.out.println("从Redis缓存中获得数据===============");
        }
        System.out.println(userListData);
    }
}

6.运行结果

  第一次运行,Redis中没有数据,此时会从数据库获取数据,并且将数据存储在Redis中,方便下次获取:
在这里插入图片描述
  第二次运行,此时Redis中存在数据,则直接从Redis中获取数据:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值