将乱码后的中文作为key放入redis后,取值时找不到key该怎么弄

本文介绍了一种在Redis中处理中文乱码的方法,通过不同字符集间的转换实现正确的数据读取。具体展示了如何将乱码后的中文数据存入Redis,并通过对应乱码格式正确取出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.redis.keynotfound;

import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import redis.clients.jedis.Builder;
import redis.clients.jedis.Client;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import redis.clients.jedis.Tuple;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.util.SafeEncoder;

public class TestKeyNotFound {

    private static Jedis jedis;

    private static Client client = null;
    protected static Pipeline pipeline = null;

    public static void initJedis() {
        jedis = new Jedis("127.0.0.1", 6379, 20000);
        client = jedis.getClient();
    }

    public Pipeline pipelined() {
        pipeline = new Pipeline();
        pipeline.setClient(client);
        return pipeline;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        initJedis();

        jedis.select(2);

        // method1();
        method2();

    }

    /**
     * 将乱码后的中文放入redis-key中,该怎么取值
     *
     * @throws UnsupportedEncodingException
     */
    private static void method1() throws UnsupportedEncodingException {
        addKeyToHash();
        // 根据key取出
        // 转为乱码格式的字符串
        String s = "天津";
        byte[] n2 = s.getBytes("gb2312");
        String gn2 = new String(n2, "utf-8");
        // 应该用对应的乱码去取

        Set<Tuple> res = jedis.zrangeWithScores("hot_projects_" + gn2, 0, -1);
        Iterator<Tuple> it = res.iterator();
        while (it.hasNext()) {
            Tuple t = it.next();

            System.out.println("element:" + t.getElement().toString() + ",score:" + t.getScore());
        }
    }

    private static void addKeyToHash() throws UnsupportedEncodingException {
        String name = "天津";
        // 插入一条
        byte[] n1 = name.getBytes("gb2312");
        String gn = new String(n1, "utf-8");
        System.out.println(gn);
        Map<String, Double> scoreMembers = new HashMap<String, Double>();
        scoreMembers.put("怡景花园", Double.valueOf(5000));
        scoreMembers.put("新福家园", Double.valueOf(500010));
        jedis.del("hot_projects_" + gn);
        jedis.zadd("hot_projects_" + gn, scoreMembers);
    }

    public static void method2() {
        String s = "hot_projects_" + "天津";
        byte[] ss = encode(s, "gb2312");
        s = SafeEncoder.encode(ss);
        Set<Tuple> res = zrangeWithScores(SafeEncoder.encode(s), 0, -1);
        for (Tuple t : res) {
            System.out.println("element:" + t.getElement().toString() + ",score:" + t.getScore());
        }
    }

    private static byte[] encode(final String str, String encodeType) {
        try {
            if (str == null) {
                throw new JedisDataException("value sent to redis cannot be null");
            }
            return str.getBytes(encodeType);
        } catch (UnsupportedEncodingException e) {
            throw new JedisException(e);
        }
    }

    private static Set<Tuple> zrangeWithScores(final byte[] key, final long start, final long end) {
        client.zrangeWithScores(key, start, end);
        return getTupledSet();
    }

    private static Set<Tuple> getTupledSet() {
        List<String> membersWithScores = client.getMultiBulkReply();
        if (membersWithScores == null) {
            return null;
        }
        if (membersWithScores.isEmpty()) {
            return Collections.emptySet();
        }
        Set<Tuple> set = new LinkedHashSet<Tuple>(membersWithScores.size() / 2, 1.0f);
        Iterator<String> iterator = membersWithScores.iterator();
        while (iterator.hasNext()) {
            set.add(new Tuple(iterator.next(), Double.valueOf(iterator.next())));
        }
        return set;
    }

    public class Queable {
        private Queue<Response<?>> pipelinedResponses = new LinkedList<Response<?>>();

        protected void clean() {
            pipelinedResponses.clear();
        }

        protected Response<?> generateResponse(Object data) {
            Response<?> response = pipelinedResponses.poll();
            if (response != null) {
                response.set(data);
            }
            return response;
        }

        protected <T> Response<T> getResponse(Builder<T> builder) {
            Response<T> lr = new Response<T>(builder);
            pipelinedResponses.add(lr);
            return lr;
        }

        protected boolean hasPipelinedResponse() {
            return !pipelinedResponses.isEmpty();
        }

        protected int getPipelinedResponseLength() {
            return pipelinedResponses.size();
        }
    }
}

 

转载于:https://my.oschina.net/iioschina/blog/857580

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值