配置文件
如果redis设置了密码,一定要写
spring:
application:
name: redis-server
database: 1 # Redis服务器数据库
host: 127.0.0.1 # Redis服务器地址
port: 6379 # Redis服务器连接端口
timeout: 6000ms # 连接超时时间(毫秒)
jedis:
pool:
max-active: 200 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 10 # 连接池中的最大空闲连接
min-idle: 0 # 连接池中的最小空闲连接
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-data-redis-reactive'
implementation 'org.springframework.data:spring-data-redis:2.2.6.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-data-redis:2.2.6.RELEASE'
Redis Config配置类
import org.springframework.cache.annotation.EnableCaching;
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.core.StringRedisTemplate;
/**
* @author : Jenson.Liu
* @date : 2020/5/14 2:07 下午
*/
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory( factory );
return redisTemplate;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
stringRedisTemplate.setConnectionFactory( factory );
return stringRedisTemplate;
}
}
函数代码
采用的是StringRedisTemplate
import com.sap.content.migrationexcel.service.RedisService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* @author : Jenson.Liu
* @date : 2020/5/14 1:43 下午
*/
@Service
public class RedisServiceImpl implements RedisService {
private final StringRedisTemplate stringRedisTemplate;
public static final int expire_time = 60*10*10;
public RedisServiceImpl(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
@Override
public void setString(String key, String value) {
stringRedisTemplate.opsForValue().set(key,value,expire_time, TimeUnit.SECONDS);
}
@Override
public String getString(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
@Override
public void setHash(String key, String hashKey, String hashValue) {
stringRedisTemplate.opsForHash().put(key,hashKey,hashValue);
stringRedisTemplate.expire(key,expire_time,TimeUnit.SECONDS);
}
@Override
public String getHashValue(String key, String hashKey) {
return stringRedisTemplate.opsForHash().get(key,hashKey).toString();
}
@Override
public boolean hasKey(String key) {
return stringRedisTemplate.hasKey(key);
}
}