在Spring Boot 中集成redis

1. 添加依赖
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
2. 配置
############################################################
### Redis 配置
############################################################
# Redis数据库索引(默认为0),如果设置为1,那么存入的key-value都存放在select 1中
spring.redis.database = 0
# Redis服务器地址
spring.redis.host = localhost
# Redis服务器连接端口
spring.redis.port = 6379
# Redis服务器连接密码(默认为空)
spring.redis.password =
#连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active = 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait = -1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle = 8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle = 0
# 连接超时时间(毫秒)
spring.redis.timeout = 0
3. 配置为Bean
@SpringBootApplication
public class DemoApplication extends WebMvcConfigurerAdapter {

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

    @Bean
    public RedisTemplate tokenRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new Jackson2JsonRedisSerializer(TokenEntity.class));
        return template;
    }
}
4. 使用
@Component
public class RedisTokenService implements TokenService {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public TokenEntity createToken(String userId) {
        String token = UUID.randomUUID().toString();
        TokenEntity tokenEntity = new TokenEntity(userId, token);
        redisTemplate.opsForValue().set(userId, tokenEntity, Constants.TOKEN_EXPIRES_HOUR, TimeUnit.MINUTES);
        return tokenEntity;
    }

    @Override
    public boolean checkToken(TokenEntity entity) {
        if (entity == null) {
            return false;
        }
        TokenEntity token = redisTemplate.opsForValue().get(entity.getUserId());
        if (token == null || StringUtils.isEmpty(token.getToken())) {
            return false;
        }
        return token.getToken().equals(entity.getToken());
    }
}

你可能感兴趣的:(在Spring Boot 中集成redis)