Spring Boot整合redis

一、添加依赖

 <!--SpringBoot整合redis的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

 

二、在配置文件中添加redis配置

 

 

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot
    username: root
    password: ROOT

  redis:
    database: 0
    host: 192.168.81.10
    password: offcn
    port: 6379

  jpa:
    database: mysql
    show-sql: true
    generate-ddl: true

 

三、编写测试类

package com.offcn.boot;
import com.offcn.HelloApplication;
import com.offcn.pojo.MUser;
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.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = HelloApplication.class)
public class TestApp {
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Test
    public void test02(){
        redisTemplate.opsForValue().set("user","xiaoming");
        String s = (String)redisTemplate.opsForValue().get("user");
        System.out.println(s);

        MUser mUser = new MUser();
        mUser.setId(5);
        mUser.setUsername("xiaohong");
        mUser.setAge(22);
        redisTemplate.opsForValue().set("muser",mUser);
       MUser muser = (MUser)redisTemplate.opsForValue().get("muser");
        System.out.println(muser);

    }
}

 

 

四、错误

通过RedisTemplate往redis中存入对象时,对象必须要实现序列化接口

 

 

 

 

 

 

posted @ 2019-11-06 20:22  我好难啊upup  阅读(182)  评论(0编辑  收藏  举报