Home  >  Article  >  Java  >  What are the ways to operate Redis in Java?

What are the ways to operate Redis in Java?

WBOY
WBOYforward
2023-04-17 21:16:011564browse

Jedis operation Redis

Create idea project

Create a Maven project and import the Jedis dependencies:

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

Create the JedisDemo test class after importing the dependencies

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());
    }
}

Outputting PONG indicates that the connection is successful~
What are the ways to operate Redis in Java?

Note:

If the Redis of the virtual machine cannot be connected during the first test, an abnormal connection failure will be reported. Two problems need to be solved:

  • First, kill the Redis process, and then modify the configuration file used to start Reids

    • Comment out the bind configuration;

    • At the same time, change the value of protected-mode to no
      What are the ways to operate Redis in Java?

  • Second step, turn off the Linux firewall (this is only used when studying, don’t do this in a production environment)

systemctl stop firewalld
systemctl disable firewalld

Anyway, this is how I solved it.

Jedis operates Redis

1. Create idea springboot project and introduce dependencies

<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. Create RedisConfig configuration class

@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;
    }

}

Simple Controller test

/**
 * @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;
    }
}

The above is the detailed content of What are the ways to operate Redis in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete