使用 Jedis API进行访问
- 导入jar包
redis.clients jedis 2.9.0
- 使用API连接
@Test
public void testConn(){
//与Redis建立连接 IP+port
Jedis redis = new Jedis("192.168.127.128", 6379);
//在Redis中写字符串 key value
redis.set("jedis:name:1","jd-zhangfei");
//获得Redis中字符串的值
System.out.println(redis.get("jedis:name:1"));
//在Redis中写list
redis.lpush("jedis:list:1","1","2","3","4","5");
//获得list的长度
System.out.println(redis.llen("jedis:list:1"));
}
2. Spring访问Redis
- 添加Redis依赖
org.springframework.data spring-data-redis 1.0.3.RELEASE
- 配置Spring.xml文件
classpath:redis.properties
- 添加redis.properties
redis.pool.maxActive=100 redis.pool.maxIdle=50 redis.pool.maxWait=1000 redis.pool.testOnBorrow=true redis.timeout=50000 redis.server=192.168.72.128 redis.port=6379
- java代码
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import java.io.Serializable;
@ContextConfiguration({ "classpath:redis.xml" })
public class RedisTest extends AbstractJUnit4SpringContextTests {
@Autowired
private RedisTemplate rt;
@Test
public void testConn() {
rt.opsForValue().set("name","zhangfei");
System.out.println(rt.opsForValue().get("name"));
}
}
3. SpringBoot访问Redis
- 添加配置文件application.yml
spring: redis: host: 192.168.72.128 port: 6379 jedis: pool: min-idle: 0 max-idle: 8 max-active: 80 max-wait: 30000 timeout: 3000
- 添加配置类RedisConfig
package com.lagou.sbr.cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Autowired
private RedisConnectionFactory factory;
@Bean
public RedisTemplate redisTemplate() {
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
}
- 测试一下
//注入RedisTemplate即可,就可以使用了 @Autowired RedisTemplate redisTemplate; redisTemplate.opsForValue().set(key,value,20, TimeUnit.SECONDS);



