Java整合Redis—Jedis
所需要的jar包
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
连接Redis的注意事项
- 禁用Linux的防火墙:Linux(CentOS7)里执行命令
systemctl stop/disable firewalld.service - redis.conf中注释掉bind 127.0.0.1 (如果指定了bind,则说明只允许来自指定网卡的Redis请求。如果没有指定,就说明可以接受来自任意一个网卡的Redis请求。)
- redis.conf中设置
protected-mode no (此时外部网络可以直接访问)
Jedis的常用操作
连接主机
Jedis jedis = new Jedis("192.168.150.101", 6379);
操作字符串
public void demo01() {
Jedis jedis = new Jedis("192.168.150.101", 6379);
jedis.set("name", "lucy");
String name = jedis.get("name");
System.out.println(name);
jedis.mset("key01", "value1", "key02", "value02");
List<String> mget = jedis.mget("key01", "key02");
for (String s : mget) {
System.out.println(mget);
}
Set<String> keys = jedis.keys("*");
for (String key : keys) {
System.out.println(key);
}
jedis.exists("key01");
Long key01 = jedis.ttl("key01");
jedis.expire("key01",200);
}
操作List
public void demo02() {
Jedis jedis = new Jedis("192.168.150.101", 6379);
jedis.lpush("k1", "lucy", "jack", "mary");
List<String> k1 = jedis.lrange("k1", 0, -1);
for (String s : k1) {
System.out.println(s);
}
jedis.lpush("user", "aaa", "bbb", "ccc");
jedis.lpush("user", "aaa");
List<String> user = jedis.lrange("user", 0, -1);
jedis.ltrim("user", 0, 1);
jedis.lpop("user");
jedis.rpush("user", "ddd");
jedis.rpop("user");
jedis.lset("user", 0, "ddd");
jedis.llen("user");
jedis.lindex("user", 0);
jedis.sort("user");
}
操作set集合
public void demo03() {
Jedis jedis = new Jedis("192.168.150.101", 6379);
jedis.sadd("username", "lucy", "jack", "mary", "lucy");
Set<String> name = jedis.smembers("username");
for (String s : name) {
System.out.println(s);
}
jedis.scard("username");
Set<String> sdiff = jedis.sdiff("username","username2");
Set<String> sinter = jedis.sinter("username", "username2");
jedis.sismember("username","lucy");
String username = jedis.spop("username");
Long smove = jedis.smove("username", "username2", "lucy");
String username1 = jedis.srandmember("username");
jedis.srem("username", "jack","lucy");
Set<String> sunion = jedis.sunion("username", "username2");
}
操作Hash
@Test
public void demo04() {
Jedis jedis = new Jedis("192.168.150.101", 6379);
jedis.hset("users", "age", "20");
String hget = jedis.hget("users", "age");
System.out.println(hget);
jedis.hdel("users","age","username");
Map<String, String> map = jedis.hgetAll("users");
Boolean hexists = jedis.hexists("users", "username");
Long users = jedis.hlen("users");
}
操作zset
public void demo05() {
Jedis jedis = new Jedis("192.168.150.101", 6379);
jedis.zadd("china", 100d, "shanghai");
Set<String> china = jedis.zrange("china", 0, -1);
System.out.println(china);
Map<String, Double> map = new HashMap<>();
map.put("b", 65.0);
map.put("c", 75.0);
map.put("d", 90.5);
jedis.zadd("score", map);
jedis.zrevrange("score", 1, 3);
Set<String> score = jedis.zrangeByScore("score", 65.0, 75);
Set<String> score1 = jedis.zrevrangeByScore("score", 75.0, 90.5);
Set<Tuple> score2 = jedis.zrangeByScoreWithScores("score", 75.0, 90.5);
Long score3 = jedis.zcount("score", 75.0, 90.5);
Double zscore = jedis.zscore("score", "b");
Long zrem = jedis.zrem("score", "a");
Long score4 = jedis.zremrangeByRank("score", 1, 2);
jedis.zremrangeByScore("score", 60.0, 85.0);
Double zincrby = jedis.zincrby("score", 6.0, "a");
}
SpringBoot整合Redis
引入相关的jar包
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- spring2.X集成redis所需common-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.0</version>
</dependency>
application.properties配置redis配置
#Redis服务器地址
spring.redis.host=192.168.150.101
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认为0)
spring.redis.database= 0
#连接超时时间(毫秒)
spring.redis.timeout=1800000
#连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=20
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=5
#连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0
redis的配置类
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setConnectionFactory(factory);
template.setKeySerializer(redisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
测试
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping
public String testRedis(){
redisTemplate.opsForValue().set("name","lucy");
String name = (String)redisTemplate.opsForValue().get("name");
redisTemplate.getExpire("name");
Boolean name1 = redisTemplate.delete("name");
redisTemplate.opsForValue().set("key01", "1", 100, TimeUnit.SECONDS);
redisTemplate.opsForValue().increment("key01", 5);
redisTemplate.opsForValue().increment("key01", -5);
return name;
}
}
Jedis的连接池工具类
public class JedisPoolUtil {
private static volatile JedisPool jedisPool = null;
private JedisPoolUtil() {
}
public static JedisPool getJedisPoolInstance() {
if (null == jedisPool) {
synchronized (JedisPoolUtil.class) {
if (null == jedisPool) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(200);
poolConfig.setMaxIdle(32);
poolConfig.setMaxWaitMillis(100 * 1000);
poolConfig.setBlockWhenExhausted(true);
poolConfig.setTestOnBorrow(true);
jedisPool = new JedisPool(poolConfig, "192.168.150.101", 6379, 60000);
}
}
}
return jedisPool;
}
public static void release(JedisPool jedisPool, Jedis jedis) {
if (null != jedis) {
jedisPool.returnResource(jedis);
}
}
}
|