redis 包
from redis import *
连接: r = StrictRedis(host='localhost', port='6379')
读写:r.set('key','value')
r.get('key')
第二种方法: pipline(缓冲命令,一次执行)
pip = r.pipline()
pip.set('key','value')
pip.get('key')
pip.execute() ---用这个方法执行缓冲的语句
===========================================================================================
java需要用 jedis包,如果需要用pool还需要commons-pool2包.
Jedis jedis = new Jedis("ip", 端口); jedis.auth("root"); .................
使用池子:
JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(100); // 最大连接数 config.setMaxIdle(10); // 最大空闲连接数 JedisPool pool = new JedisPool(config, "ip", 端口); Jedis jedis = pool.getResource(); jedis.auth("root"); .............................
使用redis集群,一个JedisShardInfo就是一个redis服务器的信息:
package com; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.*; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; /** * @author Zhai * 2019/04/01 16:56 */ public class JedisTest { public static void main(String[] args) throws URISyntaxException { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); // config配置 List<JedisShardInfo> infos = new ArrayList<>(); JedisShardInfo info = new JedisShardInfo(new URI("redis://:qwe...@127.0.0.1:6379/1")); infos.add(info); ShardedJedisPool pool = new ShardedJedisPool(config, infos); ShardedJedis resource = pool.getResource();// 从连接池获取client if (resource == null) System.out.println("获取client出错"); resource.set("key01", "value data"); resource.expire("key01", 5); // 5秒之后清除 resource.close(); pool.close(); } }
===================================================================================================================
在spring boot中使用 spring data redis, 首先添加pom文件:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
application.properties 文件配置(单个redis节点):
spring.redis.host=1.1.1.1 spring.redis.port=6379 spring.redis.password=123 spring.redis.database=0
添加bean(注意bean的名称必须为redisTemplate,这样才能覆盖默认配置):
@Bean(name = "redisTemplate") public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);//所有属性均可见 mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);//为null不参加序列化 mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);//在Redis中存储对象类信息 serializer.setObjectMapper(mapper); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(serializer); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(serializer); template.setConnectionFactory(factory); return template; }