SpringBoot中使用Jedis
1.pom依赖
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2.创建配置类
@Configuration
public class RedisConfig {
//从配置文件中获取参数注入
@Value("${redis.host:127.0.0.1}")
private String redisHost;
@Value("${redis.port:6379}")
private Integer redisPort;
@Value("${redis.password}")
private String redisPassword;
//配置连接池
@Bean
JedisPoolConfig jedisPoolConfig(){
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(10); //最大连接数
jedisPoolConfig.setMaxIdle(10); //最大空闲连接数
return jedisPoolConfig;
}
//构造一个连接池对象
@Bean
public JedisPool jedis(JedisPoolConfig jedisPoolConfig){
JedisPool jedisPool = new JedisPool(jedisPoolConfig,redisHost,redisPort,
30,redisPassword);
return jedisPool;
}
}
3.配置文件
application.properties
redis.host=172.16.2.134
redis.port=6379
redis.password=123456
4.主配置类
@SpringBootApplication
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
@Autowired
JedisPool jedisPool;
@Bean
CommandLineRunner commandLineRunner(){
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
//从池子中获取一个连接资源
Jedis jedis = jedisPool.getResource();
//通过索引选取数据库
jedis.select(0);
//String操作
String mset = jedis.mset("key1", "value1", "key2", "value2");
System.out.println(mset);
//List操作
Long lpush = jedis.lpush("k3", "k3", "kk3", "kkk3");
System.out.println(lpush); //返回最新的数据长度
//Hash操作
Map<String,String> map = new HashMap<>();
map.put("name","张三");
map.put("age","20");
Long key4 = jedis.hset("key4", map);
System.out.println(key4);
//set 不可重复,没有顺序
Long key5 = jedis.sadd("key5", "1", "2", "3", "2");
System.out.println(key5);
//zset 有序,带score属性排序
Map map1 = new HashMap();
map1.put("a",100d);
map1.put("b",80d);
map1.put("c",90d);
Long key6 = jedis.zadd("key6", map1);
System.out.println(key6);
//关闭链接,放回池子中
jedis.close();
}
};
}
}