栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

redis在springboot中使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

redis在springboot中使用

redis使用

把一些经常查询,不经常修改的可放进去

比如:将首页放进去(访问量大)

项目集成Redis 1:引入依赖

        
            org.springframework.boot
            spring-boot-starter-data-redis
        

        
        
            org.apache.commons
            commons-pool2
            2.6.0
        
2:创建配置类(固定)
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        RedisSerializer redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}
3:在所需的类上添加缓存的注解

在写逻辑的地方(实现类)

3.1:@Cacheable

查询时使用

也就是,页面调用的时候:

​ 第一次访问,查询数据库,并将查到加到缓存

​ 第二次访问,先查看缓存,如果没有,重新第一步

value:缓存名(指定了你的缓存放在哪块命名空间)

cacheNames:与 value 差不多,二选一即可

key:可选属性,可以使用 SpEL 标签自定义缓存的key

3.2:@CachePut

使用该注解标志的方法,每次都会执行,并将结果存入指定的缓存中。一般用在新增方法上。

value:缓存名(指定了你的缓存放在哪块命名空间)

cacheNames:与 value 差不多,二选一即可

key:可选属性,可以使用 SpEL 标签自定义缓存的key

3.3:@CacheEvict

使用该注解标志的方法,会清空指定的缓存。一般用在更新或者删除方法上

value:缓存名(指定了你的缓存放在哪块命名空间)

cacheNames:与 value 差不多,二选一即可

key:可选属性,可以使用 SpEL 标签自定义缓存的key

allEntries:是否清空所有缓存,默认为 false。如果指定为 true,则方法调用后将立即清空所有的缓存

beforeInvocation:是否在方法执行前就清空,默认为 false。如果指定为 true,则在方法执行前就会清空缓存

例:
@Cacheable(value = "banner", key = "'selectIndexList'")
4:启动redis

启动:redis-server /myredis/redis.conf

进入客户端:redis-cli

注:在redis配置文件中

​ 1:修改protected-mode yes为no

​ 2:注释掉:#bind 127.0.0.1

5:在配置文件中配置redis地址
#为虚拟机地址
spring.redis.host=192.168.126.128
spring.redis.port=6379
spring.redis.database= 0
spring.redis.timeout=1800000

spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0
6:当需要从redis中查询个东西时

在其内有,从redis中查询,以及将东西放入,设置有效时间

先注入

@Autowired
private RedisTemplate redisTemplate;
6.1:查询时
//根据手机号从redis获取验证码,如果成功,直接返回
String code = redisTemplate.opsForValue().get(phone);
6.2:把东西放入redis设置有效时间
redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

下面是全部的:

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("send/{phone}")
    public R msmSend(@PathVariable String phone){

        //根据手机号从redis获取验证码,如果成功,直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }

        //发送手机验证码
        //生成随机值,传递阿里云进行发送
        code= RandomUtil.getFourBitRandom();
        Map param = new HashMap<>();
        param.put("code",code);
        //调用service发送短信的方法
        boolean isSend=msmService.send(param,phone);

        if(isSend) {
            //发送成功,把发送成功验证码放到redis里面
            //设置有效时间(5分钟)
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/827636.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号