【spring-boot】Redis的整合与使用详解
在pom.xml中添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.2.1.RELEASE</version> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.1.0</version> </dependency>
添加配置文件 appliaction.yml
server:
port: 8090
servlet:
context-path: /springboot
mybatis:
# 对应实体类的包名
type-aliases-package: com.komiles.study.domain
mapper-locations: classpath:mybatis/mapper/*.xml
config-location: classpath:mybatis/mybatis-config.xml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/komo?characterEncoding=utf-8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
redis:
database: 0
host: 127.0.0.1
port: 6379
jedis:
pool:
max-active: 8
max-idle: 8
max-wait: 1ms
min-idle: 0
因为我的Redis没有设置密码,所以这个地方也没加密码。
新建User实体对象 User.java
package com.komiles.study.domain; import java.io.Serializable; import lombok.Data; @Data public class User implements Serializable { private Integer id; private String username; private String password; }
新建Controller测试入口 RedisTestController.java
package com.komiles.study.controller; import com.komiles.study.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author komiles@163.com * @date 2020-04-02 14:22 */ @RequestMapping("/redis") @RestController public class RedisTestController { @Autowired RedisTemplate redisTemplate; // 对象Redis实例 @Autowired StringRedisTemplate stringRedisTemplate; // 字符串Redis实例 @GetMapping("/strTest") public String redisStrTest() { ValueOperations<String,String> valueOperations = stringRedisTemplate.opsForValue(); valueOperations.set("name", "hello world"); String value = valueOperations.get("name"); return value; } @GetMapping("/objTest") public User redisObjTest() { ValueOperations valueOperations = redisTemplate.opsForValue(); User user = new User(); user.setId(1111); user.setUsername("哈哈哈"); user.setPassword("123456"); valueOperations.set("user_obj", user); return (User) valueOperations.get("user_obj"); } }
访问地址
注意事项:实体类中,需要实现接口 Serializable,不然在设置对象时,会报错。
参考地址:https://github.com/KoMiles/spring-example/tree/master/mybatis-generator-demo
千里之行,始于足下。改变现在,就是改变未来。改变未来,从现在开始。