在此先记录在springboot中使用redis的过程,redis的详细学习过程会在之后的笔记中进行完善。
1.在springboot项目中导入所需的starter和jedis的依赖,将客户端驱动从默认的lettuce改为jedis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.2.6.RELEASE</version>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
spring-boot-starter-data-redis(版本2.x)会依赖Lettuce的Redis客户端驱动,而在一般的项目中,我们会使用Jedis,所以在代码中使用了元素将其依赖排除了,与此同时引入了Jedis的依赖,这样就可以使用Jedis进行编程了。
2.配置属性;SpringBoot的自动装配机制就会读取这些配置来生成有关Redis的操作对象,这里它会自动生成RedisConnectionFactory、RedisTemplate、StringRedisTemplate等常用的Redis对象。
#服务器属性
spring.redis.database=1
spring.redis.port=6379
spring.redis.host=127.0.0.1
#spring.redis.password=123456
spring.redis.timeout=10000
#连接池属性
spring.redis.jedis.pool.min-idle=5
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.max-active=10
spring.redis.jedis.pool.max-wait=2000
3.将springboot提供的RedisTemplate的默认序列器修改为StringRedisSerializer
@SpringBootApplication
public class ApplicationStarter {
public static void main(String[] args) {
SpringApplication.run(ApplicationStarter.class, args);
}
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
RedisSerializer serializer=new StringRedisSerializer();
template.setDefaultSerializer(serializer);
return template;
}
}
4.Controller中使用RedisTemplate
@Controller
@SuppressWarnings("unchecked")
public class RedisController {
@Autowired
private RedisTemplate redisTemplate;
```@RequestMapping(value = "/redis")
public String redis(HttpServletRequest request,Model mod) {
log.info("redis中的登录用户 1 :"+redisTemplate.opsForValue().get("loginUser"));
String username=request.getParameter("username");
String password=request.getParameter("password");
redisTemplate.execute((RedisOperations operations)->{
operations.opsForValue().set("loginUser", username);
return null;
});
log.info("redis中的登录用户 2 :"+redisTemplate.opsForValue().get("loginUser"));
return "main";
}
}
5.postman发请求
http://127.0.0.1:8089/zone/redis?username=ljx_test&password=123456
```java
2020-05-07 22:28:20.359 INFO 7020 --- [nio-8089-exec-1] ljx.controller.RedisController : redis中的登录用户 1 :ljx_test
2020-05-07 22:28:20.365 INFO 7020 --- [nio-8089-exec-1] ljx.controller.RedisController : redis中的登录用户 2 :ljx_test