首頁  >  文章  >  Java  >  Java操作Redis的方式有哪些

Java操作Redis的方式有哪些

WBOY
WBOY轉載
2023-04-17 21:16:011601瀏覽

Jedis操作Redis

建立idea工程

建立一個Maven項目,導入Jedis依賴即可:

<!-- 导入Jedis依赖 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.2.0</version>
        </dependency>

導入依賴之後建立JedisDemo測試類別

package com.vleus.jedis;

import redis.clients.jedis.Jedis;

/**
 * @author vleus
 * @date 2021年07月03日 23:52
 */
public class JedisDemo1 {

    public static void main(String[] args) {

        //创建Jedis对象
        Jedis jedis = new Jedis("192.168.37.139",6379);
		//测试Jedis客户端是否能够连接上Redis
        System.out.println(jedis.ping());
    }
}

輸出PONG表示連線成功~
Java操作Redis的方式有哪些

注意:

第一次測試時如果連線不上虛擬機器的Redis,報連線不上的例外有兩個問題需要解決:

  • 首先,kill掉Redis的進程,然後修改Reids的啟動所使用的設定檔

    • ##註解掉bind的設定;

    • 同時將protected-mode的值改為no


      Java操作Redis的方式有哪些

    ##第二步,關掉Linux的防火牆(這裡僅是在做學習時使用,生產環境別這麼幹)
  • systemctl stop firewalld
    systemctl disable firewalld
  • 反正我是這麼解決的。

Jedis操作Redis

1、建立idea springboot項目,引入依賴

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- spring-boot-redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- spring2.x继承redis需要commons-pool -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.2</version>
        </dependency>
		<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.3</version>
        </dependency>

    </dependencies>

2、建立RedisConfig配置類別

@EnableCaching
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> 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<String> 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;
    }

}

簡單的Controller測試

/**
 * @author vleus
 * @date 2021年07月04日 13:06
 */
@RestController
@RequestMapping(value = "/redisTest")
public class RedisTestController {

    @Resource
    private RedisTemplate redisTemplate;

    @GetMapping
    public String testRedis() {
        //设置值到redis
        redisTemplate.opsForValue().set("name","jack");
        //从redis中获取值
        String name = (String) redisTemplate.opsForValue().get("name");
        return name;
    }
}

以上是Java操作Redis的方式有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除