您的位置:首页 > 数据库 > Redis

Spring boot 2.X 简单集成redis lettuce

2020-01-11 16:29 1336 查看

1、 创建spring boot 工程

可以通过IDEA自动构建springboot工程,加入redis依赖 pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.floyd.redis</groupId>
<artifactId>f-redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>f-redis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- lettuce pool 缓存连接池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

2、添加配置参数

在application.properties 文件中配置redis的各项参数

Redis数据库索引(默认0)
spring.redis.database=0
#redis服务器地址
spring.redis.host=192.168.188.122
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接超时时间(毫秒)
spring.redis.timeout=10000

# Lettuce
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.lettuce.pool.max-wait=10000
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0
# 关闭超时时间
spring.redis.lettuce.shutdown-timeout=100

现在是2.X 版本默认使用的lettuce客户端,两种客户端的区别如下

Jedis和Lettuce都是Redis Client
Jedis 是直连模式,在多个线程间共享一个 Jedis 实例时是线程不安全的,
如果想要在多线程环境下使用 Jedis,需要使用连接池,
每个线程都去拿自己的 Jedis 实例,当连接数量增多时,物理连接成本就较高了。
Lettuce的连接是基于Netty的,连接实例可以在多个线程间共享,
所以,一个多线程的应用可以使用同一个连接实例,而不用担心并发线程的数量。
当然这个也是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。
通过异步的方式可以让我们更好的利用系统资源,而不用浪费线程等待网络或磁盘I/O。
Lettuce 是基于 netty 的,netty 是一个多线程、事件驱动的 I/O 框架,
所以 Lettuce 可以帮助我们充分利用异步的优势。

2、创建RedisConfg类

@Configuration
//启用缓存
@EnableCaching
//配置节点
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConfig extends CachingConfigurerSupport {

// Redis服务器地址
@Value ("${spring.redis.host}")
private String host;
// Redis服务器连接端口
@Value("${spring.redis.port}")
private Integer port;
// Redis数据库索引(默认为0)
@Value("${spring.redis.database}")
private Integer database;
// Redis服务器连接密码(默认为空)
@Value("${spring.redis.password}")
private String password;
// 连接超时时间(毫秒)
@Value("${spring.redis.timeout}")
private Integer timeout;

// 连接池最大连接数(使用负值表示没有限制)
@Value("${spring.redis.lettuce.pool.max-active}")
private Integer maxTotal;
// 连接池最大阻塞等待时间(使用负值表示没有限制)
@Value("${spring.redis.lettuce.pool.max-wait}")
private Integer maxWait;
// 连接池中的最大空闲连接
@Value("${spring.redis.lettuce.pool.max-idle}")
private Integer maxIdle;
// 连接池中的最小空闲连接
@Value("${spring.redis.lettuce.pool.min-idle}")
private Integer minIdle;
// 关闭超时时间
@Value ("${spring.redis.lettuce.shutdown-timeout}")
private Integer shutdown;

@Bean
@Override
public CacheManager  cacheManager (){
RedisCacheWriter writer = RedisCacheWriter.nonLockingRedisCacheWriter (getRedisConnectionFactory ());

//创建默认缓存配置对象
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
RedisCacheManager cacheManager = new RedisCacheManager(writer, config);
return cacheManager;
}
//这里需要标记一个名称,否则在工具类中会注入失败
@Bean( name = "template")
public RedisTemplate<String, Object> redisTemplate() {
//创建RedisTemplate对象
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(getRedisConnectionFactory());

//将RedisTemplate的Value序列化方式由JdkSerializationRedisSerializer更换为Jackson2JsonRedisSerializer
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.setValueSerializer(jackson2JsonRedisSerializer);
//RedisTemplate对象需要指明Key序列化方式,如果声明StringRedisTemplate对象则不需要;
template.setKeySerializer(new StringRedisSerializer ());

template.afterPropertiesSet();
return template;
}

/**
* 获取缓存连接
* @return
*/
@Bean
public RedisConnectionFactory getRedisConnectionFactory(){

//创建缓存连接池
GenericObjectPoolConfig config = new GenericObjectPoolConfig ();
config.setMaxTotal(maxTotal);
config.setMaxWaitMillis(maxWait);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
LettucePoolingClientConfiguration pool = LettucePoolingClientConfiguration.builder()
.poolConfig(config)
.commandTimeout(Duration.ofMillis(timeout))
.shutdownTimeout(Duration.ofMillis(shutdown))
.build();

//单机模式
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName(host);
configuration.setPort(port);
configuration.setDatabase(database);
configuration.setPassword(RedisPassword.of(password));

return  new LettuceConnectionFactory(configuration, pool);
}

}

3、创建redis工具类

@Component
public class RedisUtil {

@Resource(name = "template")
private RedisTemplate<String,String> template;

public  boolean set(String key, String value, long validTime) {

boolean result = template.execute(new RedisCallback<Boolean> () {
@Override
public Boolean doInRedis(RedisConnection connection) throws
DataAccessException {
RedisSerializer<String> serializer = template.getStringSerializer();
connection.set(serializer.serialize(key), serializer.serialize(value));
if ( validTime > 0 ) {
connection.expire(serializer.serialize(key), validTime);
}
return true;
}
});
return result;
}

public  <T> boolean set(String key, T value) {
Gson gson = new Gson();
return set (key, gson.toJson(value),0);
}

public  <T> T get(String key, Class<T> clazz) {
Gson gson = new Gson();
return gson.fromJson(get(key), clazz);
}

public  String get(String key) {
String result = template.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer<String> serializer = template.getStringSerializer();
byte[] value = connection.get(serializer.serialize(key));
return serializer.deserialize(value);
}
});
return result;
}

public  boolean del(String key) {
return template.delete(key);
}
}

4、开始测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class FRedisApplicationTests {

private Logger logger =  LoggerFactory.getLogger (FRedisApplicationTests.class);

@Autowired
private RedisUtil  redisUtil;

@Test
public void contextLoads() {

StringBuffer  msg = new StringBuffer ();

msg.append ("set:"+redisUtil.set ("20190828", "这是第一条测试数据"));
msg.append ("\r\n");
msg.append ("get:"+redisUtil.get ("20190828"));
msg.append ("\r\n");
msg.append ("del:"+redisUtil.del ("20190828"));
logger.info ("信息:{}",msg.toString ());

msg.setLength (0);

Student  su = new Student (1,"小白",18,"一条酸菜鱼");
msg.append ("set:"+redisUtil.set("student",su));
msg.append ("\r\n");
msg.append ("get:"+redisUtil.get ("student"));
msg.append ("\r\n");
msg.append ("del:"+redisUtil.del ("student"));
logger.info ("信息:{}",msg.toString ());
}

}

测试结果:

代码下载 github

本文参考

https://www.cnblogs.com/taiyonghai/p/9454764.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
阿琪琪琪 发布了19 篇原创文章 · 获赞 0 · 访问量 1335 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: