欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

07.SpringBoot整合Redis

程序员文章站 2022-04-19 19:37:31
...

SpringBoot整合Redis

一、起步依赖

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

二、application.properties中配置连接信息

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

三、注入测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class RedisTemplateTest {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Test
    public void test() throws Exception {

        String userStr = redisTemplate.boundValueOps("user.findAll").get();

        if (userStr == null) {
            List<User> list = userRepository.findAll();
            ObjectMapper om = new ObjectMapper();
            userStr = om.writeValueAsString(list);
            redisTemplate.boundValueOps("user.findAll").set(userStr);
            System.out.println("~~~~~~~~~~ 从数据库中获取数据 ~~~~~~~~~~~~");
        } else {
            System.out.println("~~~~~~~~~~ 从Redis中获取数据 ~~~~~~~~~~~~");
        }

        System.out.println(userStr);

    }
}

转载于:https://www.jianshu.com/p/5d0471ad9c38