spring boot整合redis小Demo

1.添加相关依赖

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

2.配置信息application.yml

#DB Configuration
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    username: root
    password: toor
  jpa:
    database: mysql
    show-sql: true
    generate-ddl: true
#Redis Configuration
  redis:
    database: 0
    host: 192.168.37.10 #redis安装在虚拟机上,此处为虚拟机ip地址
    port: 6379

3.实体类User(非必须)

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "user")
@Data
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)// 主键自增长
    private Integer id;
    private String username;
    private String password;
    private String name;

    public User(String username, String password, String name) {
        this.username = username;
        this.password = password;
        this.name = name;
    }

    public User(){
        super();
    }
}

4.编写测试代码

import com.hui.MainClass;
import com.hui.entity.User;
import com.hui.mapper.UserMapper;
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.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {MainClass.class})
public class AppTest {

    @Resource
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testRedisTemplate(){
        // 存放到Redis缓存
        redisTemplate.opsForValue().set("marry","code");
        // 从Redis缓存中取值
        String str = (String) redisTemplate.opsForValue().get("marry");
        System.err.println(str);

        // 存放对象到Redis缓存
        User user = new User("root","toor","marrycode");
        redisTemplate.opsForValue().set("user",user);

        User u = (User) redisTemplate.opsForValue().get("user");
        System.err.println(u);
    }
}

运行测试代码,检查redis缓存中已添加相应的缓存,并且可以从redis缓存中读取对应数据。

原文地址:https://www.cnblogs.com/marrycode/p/11813217.html