上篇文章 Redis 服务器的安装部署 讲述了 Redis 服务器的部署。本文则从 Redis 客户端角度,讲述 Java 代码访问 Redis 的三种方式(基于官方 API、基于 Spring、基于 SpringBoot),开发者可根据自己项目所采用的框架选择。
作者:王克锋
出处:https://kefeng.wang/2017/08/22/redis-development/
版权:自由转载-非商用-非衍生-保持署名,转载请标明作者和出处。
1 基于官方 API
1.1 pom.xml
1 2 3 4 5
| <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.1</version> </dependency>
|
1.2 RedisClient.java
1 2 3 4 5 6 7 8 9 10 11
| public class RedisClient { public static void main(String[] args) { try (Jedis redis = new Jedis("localhost")) { System.out.println("auth=" + redis.auth("passwd")); System.out.println("ping=" + redis.ping()); System.out.println("keys=" + redis.keys("*")); System.out.println("type=" + redis.type("user")); System.out.println("hash=" + redis.hgetAll("user")); } } }
|
2 基于 Spring
2.1 pom.xml 中增加依赖项
1 2 3 4 5 6 7 8 9 10
| <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
1 2 3 4 5 6 7 8 9 10
| ## 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 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 中配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| <?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">
<context:property-placeholder location="classpath:config/redis.properties" />
<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>
<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>
<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(非线程安全)
1 2 3 4 5 6 7
| 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(线程安全的)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public static void demoJedisPool() { JedisPoolConfig config = new JedisPoolConfig(); config.setMinIdle(1); config.setMaxIdle(3); config.setMaxTotal(8); config.setMaxWaitMillis(1000);
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"));
}
pool.close(); }
|
2.7 方式3:Spring 方式(连接池、线程安全)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @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
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
|
3.2 application.properties
1 2 3 4 5 6 7 8 9 10
| ### 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>
。
1 2 3 4 5 6 7 8 9 10 11 12 13
| @RestController 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); } }
|