talk is cheap,show you my code
方法一:使用jedis(Jedis是Redis官方推荐的面向Java的操作Redis的客户端,详细文档可见jedis文档)
0.当然,首先你要先安装redis数据库,不会安装的自行百度(ubuntu:apt-get install redis-server)
1.创建Springboot项目
2.在pom文件中导入jedis
和fastjason
的依赖(因为redis存储的方式为二进制存储,所以使用fastjson进行序列化)
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.50</version>
</dependency>
3.在application.properties中配置redis相关参数
#redis
redis.host=127.0.0.1
redis.port=6379
redis.password=#你自己的数据库密码,默认为空
redis.timeout=2000
redis.poolMaxTotal=10
redis.poolMaxIdle=10
reids.poolMaxWait=3
redis.db=0
4.创建redis
包,在包下新建RedisConfig
类
package com.wantao.jedis.redis;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Redis的配置类
*/
@Component
@ConfigurationProperties(prefix = "redis")
@Data
public class RedisConfig {
private String host;
private int port;
private String password;
private int timeout;
private int poolMaxTotal;
private int poolMaxIdle;
private int poolMaxWait;
private int db;
}
5.在包下新建RedisPoolFactory
类,用来获取JedisPool
对象,进而通过jedisPool.getResource()
方法获得Jedis
对象
package com.wantao.jedis.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
*创建RedisPool对象
*/
@Component
public class RedisPoolFactory {
@Autowired
private RedisConfig redisConfig;
@Bean
public JedisPool getJedisPool(){
JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
jedisPoolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait(