redis项目上使用

  1. pom文件
        <!-- redis -->
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
          <exclusions>
            <exclusion>
              <groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId>
            </exclusion>
          </exclusions>
        </dependency>
        <dependency>
          <groupId>redis.clients</groupId>
          <artifactId>jedis</artifactId>
          <version>3.6.1</version>
        </dependency>

     

  2. 配置文件
    spring:
      redis:
        host: localhost
        port: 6379

     

  3. 代码
    @Configuration
    public class RedisConfig {
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
    
            //设置Redis链接工厂对象
            template.setConnectionFactory(connectionFactory);
    
            // 设置String键z值的序列化方式为 String
            template.setKeySerializer(new StringRedisSerializer());
            //设置value序列化
            template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    
            // 设置Hash Key键值的序列化方式为 JSON
            template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
            template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
    
            return template;
        }
    }

     

  4. 使用和获取
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
    
        @GetMapping("/useRedis")
        public String useRedis(){
            redisTemplate.opsForValue().set("USER_KEY_PREFIX",115);
            return "";
        }
    
        @GetMapping("/getRedis")
        public String getUserById() {
            Object user = redisTemplate.opsForValue().get("USER_KEY_PREFIX");
            return user.toString();
        }

     

posted @ 2024-12-20 11:17  baihehua  阅读(15)  评论(0)    收藏  举报