Redis 客户端的开发

上篇文章 Redis 服务器的安装部署 讲述了 Redis 服务器的部署。本文则从 Redis 客户端角度,讲述 Java 代码访问 Redis 的三种方式(基于官方 API、基于 Spring、基于 SpringBoot),开发者可根据自己项目所采用的框架选择。

作者:王克锋
出处:https://kefeng.wang/2017/08/22/redis-development/
版权:自由转载-非商用-非衍生-保持署名,转载请标明作者和出处。

1 基于官方 API

1.1 pom.xml

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.8.1</version>
</dependency>

1.2 RedisClient.java

public class RedisClient {
    public static void main(String[] args) {
        try (Jedis redis = new Jedis("localhost")) {
            System.out.println("auth=" + redis.auth("passwd")); // OK
            System.out.println("ping=" + redis.ping()); // PONG
            System.out.println("keys=" + redis.keys("*")); // [user, key]
            System.out.println("type=" + redis.type("user")); // hash
            System.out.println("hash=" + redis.hgetAll("user")); // hash
        }
    }
}

2 基于 Spring

2.1 pom.xml 中增加依赖项

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.8.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.7.2.RELEASE</version>
</dependency>

2.2 新建配置文件 redis.properties

## redis
redis.host=localhost
redis.port=6379
redis.pass=passwd

redis.maxTotal=8
redis.maxIdle=3
redis.minIdle=1
redis.maxWaitMillis=1000
redis.testOnBorrow=true

2.3 新建序列化类 FastJsonRedisSerializer.java

public class FastJsonRedisSerializer implements RedisSerializer<Object> {
    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    public byte[] serialize(Object obj) throws SerializationException {
        if (obj == null) {
            return new byte[0];
        }

        SerializerFeature features = SerializerFeature.WriteClassName;
        return JSON.toJSONString(obj, features).getBytes(DEFAULT_CHARSET);
    }

    public Object deserialize(byte[] raw) throws SerializationException {
        if (raw == null || raw.length <= 0) {
            return null;
        }

        String str = new String(raw, DEFAULT_CHARSET);
        return JSON.parseObject(str, Object.class);
    }
}

2.4 spring.xml 中配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:redis="http://www.springframework.org/schema/redis"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/redis http://www.springframework.org/schema/redis/spring-redis-1.0.xsd">

    <!-- 导入 Redis 配置 -->
    <context:property-placeholder location="classpath:config/redis.properties" />

    <!-- Redis 连接池选项 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.maxTotal}" />
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>

    <!-- Redis 服务配置 -->
    <bean id="jedisFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.host}" />
        <property name="port" value="${redis.port}" />
        <property name="password" value="${redis.pass}" />
        <property name="usePool" value="true" />
        <property name="poolConfig" ref="jedisPoolConfig" />
    </bean>

    <!-- Redis 模板配置 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisFactory" />
        <property name="enableTransactionSupport" value="false" />
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean class="wang.kefeng.demo.service.FastJsonRedisSerializer" />
        </property>
    </bean>

</beans>

2.5 方式1:单一 Jedis(非线程安全)

public static void demoJedisClient() {
    Jedis jedis = new Jedis("localhost", 6379);
    jedis.auth("passwd");
    jedis.set("name", "client");
    logger.info("name={}", jedis.get("name"));
    jedis.close();
}

2.6 方式2:使用 JedisPool(线程安全的)

public static void demoJedisPool() {
    // 准备连接池参数
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMinIdle(1); // 最小空闲连接数
    config.setMaxIdle(3); // 最大空闲连接数
    config.setMaxTotal(8); // 最大连接数
    config.setMaxWaitMillis(1000); // 最大阻塞时(ms)

    // 创建连接池[单一部署]
    Pool<Jedis> pool = null;
    pool = new JedisPool(config, "localhost", 6379);

    // 使用连接
    try (Jedis jedis = pool.getResource()) {
        jedis.auth("passwd");
        jedis.set("name", "pool");
        logger.info("name={}", jedis.get("name"));

        // auto call jedis.close();
        // Jedis对 close() 作了改造,非连接池情形下,是关闭连接;
        // 连接池情形下,是把连接对象返回到对象池,而不是关闭。
    }

    // 销毁连接池
    pool.close();
}

2.7 方式3:Spring 方式(连接池、线程安全)

@SuppressWarnings("unchecked")
public static void demoJedisSpring() {
    String file = "spring/redis.xml";
    try (ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(file)) {
        RedisTemplate<String, Object> template = (RedisTemplate<String, Object>) ctx.getBean(RedisTemplate.class);
        ValueOperations<String, Object> jedis = template.opsForValue();

        Map<String, Object> maps = new HashMap<>();
        maps.put("name", "kevin");
        maps.put("age", 123);
        jedis.set("student", maps);

        Object obj = jedis.get("student");
        logger.info("name={}", obj.getClass().getName());
    }
}

3.基于 SpringBoot

3.1 pom.xml

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

3.2 application.properties

### Redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=passwd
spring.redis.database=0
spring.redis.timeout=3000
spring.redis.pool.min-idle=3
spring.redis.pool.max-idle=8
spring.redis.pool.max-active=16
spring.redis.pool.max-wait=3000

3.3 demoJedisClient.java

其中的 StringRedisTemplate 相当于 spring-data-redis 中的 RedisTemplate<String, String>

@RestController // 指定数据格式为 JSON(Apache Jackson)
public class demoJedisClient {
    @Autowired
    private StringRedisTemplate stringTemplate;

    @RequestMapping("/hello")
    public String hello() {
        String name = "test:time";
        String value = Long.toString(System.currentTimeMillis());
        stringTemplate.opsForValue().set(name, value);
        return stringTemplate.opsForValue().get(name);
    }
}

猜你喜欢

转载自blog.csdn.net/kefengwang/article/details/81177602