Redis做缓存springboot

话不多说,demo走起
pom文件引入

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
  		<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
 
   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
 
   <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
 
   <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.5.0</version>
        </dependency>
    </dependencies>

application.properties配置文件

#redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.timeout=60s
# 数据库连接超时时间,2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位
#spring.redis.timeout=60s
# 连接池配置,2.0中直接使用jedis或者lettuce配置连接池
# 最大活跃连接数,负数为不限制
spring.redis.lettuce.pool.max-active=500
# 等待可用连接的最大时间,负数为不限制
spring.redis.lettuce.pool.max-wait=-1ms
# 最大空闲连接数
spring.redis.lettuce.pool.max-idle=100
# 最小空闲连接数
spring.redis.lettuce.pool.min-idle=20

servers层的实现类

package com.hjf.services.impl;
 
import com.hw.entity.Student;
import com.hw.mapper.StudentsMapper;
import com.hw.services.StudentsServices;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
 
import java.util.List;

@Service
public class StudentsServicesImpl implements StudentsServices {
    @Autowired
    private StudentsMapper studentsMapper;
 
 
    @Cacheable(value = "student", key = "#root.targetClass", unless = "#result eq null")
    @Override
    public List<Student> getAllStudents() {
        return studentsMapper.getAllStudents();
    }
 
    @CacheEvict(value = "student",key = "#root.targetClass", condition ="#result gt 0")
    @Override
    public int addStudent(Student student){
        return studentsMapper.addStudent(student);
    }
}

解释一下
注解@Cacheable标记在一个方法上时表示该方法是支持缓存的,当标记在一个类上时则表示该类所有的方法都是支持缓存的,Spring会在其被调用后将其返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果,而不需要再次执行该方法
@CacheEvict则是在redis删除这个缓存

import com.hw.entity.Student;
import com.hw.services.StudentsServices;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.List;
import java.util.UUID;
 
/**
 * @program: Maven
 * @description:
 * @author: hw
 **/
@RestController
public class selectStudentController {
    @Autowired  //注入    完成自动装配
    private StudentsServices studentsServices;
 
    @RequestMapping("/getStudents")
    public List<Student> getAllStudents(){
        System.out.println("集合长度:"+studentsServices.getAllStudents().size());
        return studentsServices.getAllStudents();
    }
 
    @RequestMapping("/hello")
    public String hello(){
        return "你好,boot-ssm";
    }
 
    @RequestMapping("/add")
    public String addStudent(){
        Student student=new Student(UUID.randomUUID().toString(),1);
        studentsServices.addStudent(student);
        return "添加成功";
    }
}

版权声明:本文为CSDN博主「beyond丿q:1559810637」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_41594146/article/details/85885423

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中使用 Redis 缓存登录的一般步骤如下: 1. 添加 Redis 依赖 在 pom.xml 文件中添加 Redis 的依赖,例如: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置 Redis 连接信息 在 application.properties 或 application.yml 文件中配置 Redis 连接信息,例如: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= ``` 3. 编写 Redis 配置类 在 Spring Boot 中,我们可以通过编写配置类来配置 RedisTemplate 和 StringRedisTemplate,例如: ```java @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) { return new StringRedisTemplate(factory); } @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager .RedisCacheManagerBuilder .fromConnectionFactory(factory); return builder.build(); } } ``` 其中,我们配置了 RedisTemplate 和 StringRedisTemplate 的序列化器为 Jackson2JsonRedisSerializer,这样可以方便地将对象序列化成 JSON 字符串存储到 Redis 中。 4. 在登录模块中使用 Redis 缓存 在登录模块中,我们可以使用 Redis 缓存用户信息。例如,我们可以将用户信息存储到 Redis 中,并设置一个过期时间,下次登录时如果 Redis 中存在该用户信息,则直接从 Redis 中获取,否则需要重新登录并将用户信息存储到 Redis 中。 ```java @Service public class UserService { @Autowired private RedisTemplate<String, Object> redisTemplate; public User login(String username, String password) { // 查询数据库,验证用户名和密码 User user = userRepository.findUserByUsernameAndPassword(username, password); if (user != null) { // 将用户信息存储到 Redis 中,并设置过期时间为 1 小时 redisTemplate.opsForValue().set("user:" + user.getId(), user, 1, TimeUnit.HOURS); } return user; } public User getUserById(Long userId) { // 先从 Redis 中获取用户信息 User user = (User) redisTemplate.opsForValue().get("user:" + userId); if (user == null) { // 如果 Redis 中不存在该用户信息,则查询数据库,并将用户信息存储到 Redis 中 user = userRepository.findById(userId).orElse(null); if (user != null) { redisTemplate.opsForValue().set("user:" + userId, user, 1, TimeUnit.HOURS); } } return user; } } ``` 在上述代码中,我们使用 redisTemplate 对象来操作 Redis 缓存,其中: - opsForValue() 方法用于操作 Redis 中的字符串类型数据; - set() 方法用于将数据存储到 Redis 中; - get() 方法用于从 Redis 中获取数据。 另外,我们还可以使用 @Cacheable 和 @CacheEvict 注解来更加方便地实现 Redis 缓存。例如: ```java @Service public class UserService { @Autowired private UserRepository userRepository; @Cacheable(value = "user", key = "#userId") public User getUserById(Long userId) { return userRepository.findById(userId).orElse(null); } @CacheEvict(value = "user", key = "#user.id") public void updateUser(User user) { userRepository.save(user); } } ``` 在上述代码中,我们使用了 @Cacheable 和 @CacheEvict 注解来实现 Redis 缓存。其中: - @Cacheable(value = "user", key = "#userId") 表示将 getUserById 方法的返回值缓存Redis 中,缓存的 key 为 user:userId; - @CacheEvict(value = "user", key = "#user.id") 表示将 updateUser 方法中传入的用户信息从 Redis 缓存中删除,缓存的 key 为 user:userId。 这样,我们就可以方便地使用 Redis 缓存登录信息了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值