spring整合redis

2023/6/7 java

# 1.安装依赖

由于Redis数据与Java类交互时需要转换成GSON格式的数据,因此还需要引入GSON的依赖包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.0</version>
</dependency>

# 2.配置redis连接

spring.data.redis.host=localhost
spring.data.redis.port=6379

3.编写启动类

Spring Boot在连接Redis时,不需要像连接MySQL数据库那样指定驱动类,所以本项目的启动类需要在@SpringBootApplication注解中通过exclude参数排除数据库的驱动程序,否则在运行启动类启动本项目时会看到错误提示,同时无法启动本项目

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class SpringBootApp {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApp.class, args);
    }
}

# 3.增删改查

@Repository
public class StudentDao  {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //向Redis缓存里保存Student数据
    public void saveStudent(String id, int expireTime, Student student){
   	    Gson gson = new Gson();
        redisTemplate.opsForValue().set(id, gson.toJson(student), expireTime, TimeUnit.SECONDS);
    }
    //从Redis缓存里根据id查找Student数据
    public Student findByID(String id){
        Gson gson = new Gson();
        Student student = null;
        String studentJson = redisTemplate.opsForValue().get(id);
        if(studentJson != null && !studentJson.equals("")){
            student =  gson.fromJson(studentJson, Student.class);
        }
        return student;
    }
    //从Redis里删除指定id的Student数据
    public void deleteByID(String id){
    	 redisTemplate.opsForValue().getOperations().delete(id);
    }
}

# 4.整合mysql和redis

1.编写启动类

@SpringBootApplication
public class SurveyApplication {
	public static void main(String[] args){
		SpringApplication.run(SurveyApplication.class, args);
	}
}

2.redis缓存类

import com.google.gson.Gson;
import com.z.entity.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

@Repository
public class UserRedis {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void saveUserInfo(String id,int expireTime,UserVo userVo){
        Gson gson = new Gson();
        redisTemplate.opsForValue().set(id,gson.toJson(userVo),expireTime,TimeUnit.SECONDS);
    }

    public UserVo getUserInfoById(String id){
        Gson gson = new Gson();
        UserVo userVo = null;
        String userVoJson = redisTemplate.opsForValue().get(id);
        if(userVoJson != null && !userVoJson.equals("")){
            userVo = gson.fromJson(userVoJson,UserVo.class);
        }
        return userVo;
    }
}

3.获取数据

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Autowired
    private UserRedis userRedis;
    @Override
    public UserVo getUserInfoById(String id) {

        Random rand = new Random();

        UserVo userInfo = userRedis.getUserInfoById(id);

        if(userInfo!=null){
            log.info("从redis获取用户信息");
            return userInfo;
        }else {
            QueryWrapper<User> w = new QueryWrapper<>();
            w.eq("id",id);
            User user = userMapper.selectOne(w);
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);

            if(user!=null){
                int randNum = rand.nextInt(100);
                userRedis.saveUserInfo(id,24 * 60 * 60 + randNum,userVo);
            }
            return userVo;
        }
    }
}

4.结果

2023-06-07 11:25:00 |INFO  |com.z.service.impl.UserServiceImpl |从redis获取用户信息