简体   繁体   English

RedisTemplate 春季启动

[英]RedisTemplate Spring boot

I am going to store my token in redis我打算将我的令牌存储在 redis 中

RedisConfig Redis配置

@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName("127.0.0.1");
        redisStandaloneConfiguration.setPort(6379);


        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration);
        return jedisConnectionFactory;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate() {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

Service服务

final var st =AuthenticationSuccessDto
                .builder()
                .accessToken(jwtUtils.generateAccessToken(user))
                .refreshToken(jwtUtils.generateRefreshToken(user))
                .tokenType("Bearer")
                .user(user)
                .expiresIn(TimeUnit.SECONDS.toSeconds(60)).build();

        try {
            redisTemplate.opsForHash().put(KEY,"1",st.getAccessToken());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception();
        }

        return st;
    }

throws an exception java.lang.NoSuchMethodError: 'long redis.clients.jedis.Jedis.hset(byte[], byte[], byte[])'抛出异常 java.lang.NoSuchMethodError: 'long redis.clients.jedis.Jedis.hset(byte[], byte[], byte[])'

I need to convert string to bytes?我需要将字符串转换为字节? help plz请帮忙

You can also have Spring Boot automatically generate the connection to Redis based on your.yml or a.properties file.您还可以让 Spring Boot 根据您的 .yml 或 a.properties 文件自动生成与 Redis 的连接。 You just need to add the following to your application.yml:您只需要将以下内容添加到您的 application.yml 中:

spring:
  redis:
    host: localhost
    port : '6379'

Everything worked for me when I changed the connection to the redis from JedisConnectionFactory to LettuceConnectionFactory当我将与 redis 的连接从 JedisConnectionFactory 更改为 LettuceConnectionFactory 时,一切都对我有用

@Bean
    public LettuceConnectionFactory redisStandAloneConnectionFactory() {
        return new LettuceConnectionFactory(new RedisStandaloneConfiguration("127.0.0.1", 6379));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM