• Java连接操作redis


    1,jedis

    redis官方推荐使用jedis操作redis

    导入依赖

    <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>3.3.0</version>
            </dependency>

    直接使用即可

    import redis.clients.jedis.Jedis;
    
    public class RedisTest {
        public static void main(String[] args) {
            Jedis jedis = new Jedis("127.0.0.1", 6379);
            System.out.println(jedis.ping());
            jedis.set("name", "zl");
            System.out.println(jedis.get("name"));
            jedis.lpush("list", "a");
            jedis.lpush("list", "b");
            jedis.lpush("list", "c");
            jedis.lpush("list", "d");
            System.out.println(jedis.lrange("list", 0, -1));
            System.out.println(jedis.keys("*"));
        }
    }

    注意:当多线程使用同一个连接时,是线程不安全的。所以要使用连接池,为每个jedis实例分配一个连接。

    2,Lettuce

    springBoot2.x之后默认集成了Lettuce

    相较于jedis,当多线程使用同一连接实例时,它是线程安全的。

    依赖引入(创建springboot项目时勾选noSQL中的redis)

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

    一般情况下不直接使用Lettuce,会手动封装一个操作redis的工具类,这个网上有很多,一下提供做参考

    package com.zl.utils;
    
    import org.apache.tomcat.util.buf.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Component;
    
    import java.util.Collection;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.TimeUnit;
    
    /**
     * Redis工具类,使用之前请确保RedisTemplate成功注入
     *
     * @author ye17186
     * @version 2019/2/22 10:48
     */
    @Component
    public class RedisUtils {
    
        private RedisUtils() {
        }
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        /**
         * 设置有效时间
         *
         * @param key Redis键
         * @param timeout 超时时间
         * @return true=设置成功;false=设置失败
         */
        public boolean expire(final String key, final long timeout) {
    
            return expire(key, timeout, TimeUnit.SECONDS);
        }
    
        /**
         * 设置有效时间
         *
         * @param key Redis键
         * @param timeout 超时时间
         * @param unit 时间单位
         * @return true=设置成功;false=设置失败
         */
        public boolean expire(final String key, final long timeout, final TimeUnit unit) {
    
            Boolean ret = redisTemplate.expire(key, timeout, unit);
            return ret != null && ret;
        }
    
        /**
         * 删除单个key
         *
         * @param key 键
         * @return true=删除成功;false=删除失败
         */
        public boolean del(final String key) {
    
            Boolean ret = redisTemplate.delete(key);
            return ret != null && ret;
        }
    
        /**
         * 删除多个key
         *
         * @param keys 键集合
         * @return 成功删除的个数
         */
        public long del(final Collection<String> keys) {
    
            Long ret = redisTemplate.delete(keys);
            return ret == null ? 0 : ret;
        }
    
        /**
         * 存入普通对象
         *
         * @param key Redis键
         * @param value 值
         */
        public void set(final String key, final Object value) {
    
            redisTemplate.opsForValue().set(key, value, 1, TimeUnit.MINUTES);
        }
    
        // 存储普通对象操作
    
        /**
         * 存入普通对象
         *
         * @param key 键
         * @param value 值
         * @param timeout 有效期,单位秒
         */
        public void set(final String key, final Object value, final long timeout) {
    
            redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
        }
    
        /**
         * 获取普通对象
         *
         * @param key 键
         * @return 对象
         */
        public Object get(final String key) {
    
            return redisTemplate.opsForValue().get(key);
        }
    
        // 存储Hash操作
    
        /**
         * 往Hash中存入数据
         *
         * @param key Redis键
         * @param hKey Hash键
         * @param value 值
         */
        public void hPut(final String key, final String hKey, final Object value) {
    
            redisTemplate.opsForHash().put(key, hKey, value);
        }
    
        /**
         * 往Hash中存入多个数据
         *
         * @param key Redis键
         * @param values Hash键值对
         */
        public void hPutAll(final String key, final Map<String, Object> values) {
    
            redisTemplate.opsForHash().putAll(key, values);
        }
    
        /**
         * 获取Hash中的数据
         *
         * @param key Redis键
         * @param hKey Hash键
         * @return Hash中的对象
         */
        public Object hGet(final String key, final String hKey) {
    
            return redisTemplate.opsForHash().get(key, hKey);
        }
    
        /**
         * 获取多个Hash中的数据
         *
         * @param key Redis键
         * @param hKeys Hash键集合
         * @return Hash对象集合
         */
        public List<Object> hMultiGet(final String key, final Collection<Object> hKeys) {
    
            return redisTemplate.opsForHash().multiGet(key, hKeys);
        }
    
        // 存储Set相关操作
    
        /**
         * 往Set中存入数据
         *
         * @param key Redis键
         * @param values 值
         * @return 存入的个数
         */
        public long sSet(final String key, final Object... values) {
            Long count = redisTemplate.opsForSet().add(key, values);
            return count == null ? 0 : count;
        }
    
        /**
         * 删除Set中的数据
         *
         * @param key Redis键
         * @param values 值
         * @return 移除的个数
         */
        public long sDel(final String key, final Object... values) {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count == null ? 0 : count;
        }
    
        // 存储List相关操作
    
        /**
         * 往List中存入数据
         *
         * @param key Redis键
         * @param value 数据
         * @return 存入的个数
         */
        public long lPush(final String key, final Object value) {
            Long count = redisTemplate.opsForList().rightPush(key, value);
            return count == null ? 0 : count;
        }
    
        /**
         * 往List中存入多个数据
         *
         * @param key Redis键
         * @param values 多个数据
         * @return 存入的个数
         */
        public long lPushAll(final String key, final Collection<Object> values) {
            Long count = redisTemplate.opsForList().rightPushAll(key, values);
            return count == null ? 0 : count;
        }
    
        /**
         * 往List中存入多个数据
         *
         * @param key Redis键
         * @param values 多个数据
         * @return 存入的个数
         */
        public long lPushAll(final String key, final Object... values) {
            Long count = redisTemplate.opsForList().rightPushAll(key, values);
            return count == null ? 0 : count;
        }
    
        /**
         * 从List中获取begin到end之间的元素
         *
         * @param key Redis键
         * @param start 开始位置
         * @param end 结束位置(start=0,end=-1表示获取全部元素)
         * @return List对象
         */
        public List<Object> lGet(final String key, final int start, final int end) {
            return redisTemplate.opsForList().range(key, start, end);
        }
    }
    RedisUtils.java

    另外根据需要重新配置redisConfig

    package com.zl.config;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    import java.net.UnknownHostException;
    
    @Configuration
    public class RedisConfig {
    
        @Bean
        @SuppressWarnings("all")
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
                throws UnknownHostException {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(redisConnectionFactory);
    
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    
            //String序列化
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            template.setKeySerializer(stringRedisSerializer);
            template.setHashKeySerializer(stringRedisSerializer);
            template.setValueSerializer(jackson2JsonRedisSerializer);
            template.setHashValueSerializer(jackson2JsonRedisSerializer);
            template.afterPropertiesSet();
    
    
            return template;
        }
    
    }
    RedisConfig.java

    最后测试操作

    package com.zl;
    
    import com.zl.utils.RedisUtils;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.redis.core.RedisTemplate;
    
    @SpringBootTest
    class RedisSpringbootApplicationTests {
        
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Autowired
        private RedisUtils redisUtils;
    
        //原生Lettuce操作
        @Test
        void contextLoads() {
            redisTemplate.opsForValue().set("name", "zlzl4");
            System.out.println(redisTemplate.opsForValue().get("name"));
        }
    
        //redisUtils操作
        @Test
        public void test1() {
            redisUtils.set("hello", "world");
            System.out.println(redisUtils.get("hello"));
        }
    
    }
  • 相关阅读:
    linux根目录空间不足
    兴趣点 / 关键点( Interest point/Keypoint )
    opencv批量修改图片尺寸
    Excel批量修改文件
    xm数据写入
    opencv矩阵操作
    SVM参数解析
    Mat取行或列
    clone()与image和 cloneTo()
    最大连通域(指针)
  • 原文地址:https://www.cnblogs.com/zhulei2/p/13803297.html
Copyright © 2020-2023  润新知