spring boot整合redis小Demo

2021年11月23日 阅读数:3
这篇文章主要向大家介绍spring boot整合redis小Demo,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

1.添加相关依赖java

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

2.配置信息application.ymlmysql

#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(非必须)redis

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.编写测试代码spring

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缓存中读取对应数据。sql

上一篇: redis的基本命令
下一篇: Redis的安装部署