SpringBoot+mysql+Redis整合增删改查操作
前言:
1.项目结构
2.实现步骤
2.1.通过SpringInitializr创建SpringBoot项目。(操作请参考上篇:SpringBoot入门)
2.2创建User类与UserDao
2.3创建RedisConfig模板类
2.4创建service类
2.5创建Controller类
2.6 application.yml配置详细
2.7 配置文件pom.xml
3.效果展示:
前言:
本文通过记录SpringBoot+springMVC+redis+mysql来实现web项目中增删改查的具体操作。redis做缓存数据库,针对于频繁需要查询或者解决单点问题都会把数据存到redis来分担服务器压力。
1.项目结构
webdemo1
java
|_________bean
|_________config(redis模板类)
|_________controller
|_________mapper
|_________service
|______Webdemo1Application(springboot启动类)
resources
|_________application.yml
2.实现步骤
2.1.通过SpringInitializr创建SpringBoot项目。
2.2创建User类与UserDao
User类:
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String userName;
private String passWord;
private Integer sex;
private Date birthday;
//setter and getter method
}
mysql表结构:
create table t_user(
id int(11) auto_increment comment '编号',
user_name varchar(50) default '' comment '用户名称',
pass_word varchar(50) default '' comment '用户密码',
sex int(3) default null comment '年龄',
birthday datetime comment '生日',
primary key (id)
)engine=innodb auto_increment =1 comment '用户表';
UserDao类:
@Repository
@Mapper
public interface UserDao {
//用户列表
@Select("select * from t_user")
@Results({
@Result(property = "userName",column = "user_name"),
@Result(property = "passWord",column = "pass_word")
})
List<User> queryAll();
//根据id获取user
@Select("select * from t_user where id =#{id}")
@Results({
@Result(property = "userName",column = "user_name"),
@Result(property = "passWord",column = "pass_word")
})
User findUserById(Integer id);
//根据id修改user
@Update("update t_user set user_name=#{userName},pass_word =#{passWord},sex=#{sex},birthday=#{birthday} WHERE id = #{id} ")
int updateUser(User user);
//根据id删除用户
@Delete("delete from t_user where id = #{id}")
int deleteUserById(Integer id);
}
2.3创建RedisConfig模板类
/**
* 配置redistemplate序列化
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* 选择redis作为默认缓存工具
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
//设置缓存有效一小时
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.
defaultCacheConfig().entryTtl(Duration.ofHours(1));
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)).cacheDefaults(redisCacheConfiguration).build();
}
/**
* 配置redistemplate相关配置
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
/**
* 对hash类型的数据操作
*/
public HashOperations<String,String,Object> hashOperations(RedisTemplate<String,Object> redisTemplate){
return redisTemplate.opsForHash();
}
/**
* 对redis字符串类型数据库操作
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 对链表类型的数据操作
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 对无序集合Set操作
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 对有序集合
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
2.4创建service类
@Service
public class UserService {
@Autowired
private UserDao userDao;
@Autowired
private RedisTemplate redisTemplate;
//查所有用户
public List<User> queryAll(){
return userDao.queryAll();
}
/**
* 获取用户策略:先从缓存中获取用户,没有则读mysql数据,再将数据写入缓存
*/
public User findUserById(int id){
String key = "user_"+id;
ValueOperations<String,User> operations = redisTemplate.opsForValue();
//判断redis中是否有键为key的缓存
boolean hasKey = redisTemplate.hasKey(key);
if(hasKey){
User user = operations.get(key);
System.out.println("从缓存中获取数据:"+user.getUserName());
System.out.println("-----------------------------");
return user;
}else{
User user = userDao.findUserById(id);
System.out.println("查询数据库获取数据:"+user.getUserName());
System.out.println("------------写入缓存---------------------");
//写入缓存
operations.set(key,user,5, TimeUnit.HOURS);
return user;
}
}
//删除用户策略:删除数据表中数据,然后删除缓存
public int deleteUserById(int id){
int result = userDao.deleteUserById(id);
String key = "user_"+id;
if(result!=0){
boolean hasKey = redisTemplate.hasKey(key);
if(hasKey){
redisTemplate.delete(key);
System.out.println("删除了缓存中的key:"+key);
}
}
return result;
}
/**
* 更新用户策略:先更新数据表,成功之后,删除原来的缓存,再更新缓存
*/
public int updateUser(User user) {
ValueOperations<String, User> operations = redisTemplate.opsForValue();
int result = userDao.updateUser(user);
if (result != 0) {
String key = "user_" + user.getId();
boolean haskey = redisTemplate.hasKey(key);
if (haskey) {
redisTemplate.delete(key);
System.out.println("删除缓存中的key-----------> " + key);
}
// 再将更新后的数据加入缓存
User userNew = userDao.findUserById(user.getId());
if (userNew != null) {
operations.set(key, userNew, 3, TimeUnit.HOURS);
}
}
return result;
}
}
2.5创建Controller类
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/queryAll")
public List<User> queryAll(){
List<User> lists = userService.queryAll();
return lists;
}
@RequestMapping("/findUserById")
public Map<String, Object> findUserById(@RequestParam int id){
User user = userService.findUserById(id);
Map<String, Object> result = new HashMap<>();
result.put("id", user.getId());
result.put("userName", user.getUserName());
result.put("pwd", user.getPassWord());
result.put("sex", user.getSex());
result.put("birthday",user.getBirthday());
return result;
}
@RequestMapping("/updateUser")
public String updateUser(){
User user = new User();
user.setId(1);
user.setUserName("AAAAA");
user.setPassWord("123456");
user.setSex(1);
user.setBirthday(new Date());
int result = userService.updateUser(user);
if(result != 0){
return "update user success";
}
return "fail";
}
@RequestMapping("/deleteUserById")
public String deleteUserById(@RequestParam int id){
int result = userService.deleteUserById(id);
if(result != 0){
return "delete success";
}
return "delete fail";
}
}
2.6 application.yml配置详细
server:
port: 8081
#数据库连接
spring:
datasource:
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
## Redis 配置
redis:
## Redis数据库索引(默认为0)
database: 0
## Redis服务器地址
host: 127.0.0.1
## Redis服务器连接端口
port: 6379
## Redis服务器连接密码(默认为空)
password:
jedis:
pool:
## 连接池最大连接数(使用负值表示没有限制)
#spring.redis.pool.max-active=8
max-active: 8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
#spring.redis.pool.max-wait=-1
max-wait: -1
## 连接池中的最大空闲连接
#spring.redis.pool.max-idle=8
max-idle: 8
## 连接池中的最小空闲连接
#spring.redis.pool.min-idle=0
min-idle: 0
## 连接超时时间(毫秒)
timeout: 1200
#将themilef的默认缓存禁用,热加载生效
thymeleaf:
cache: false
#mybatis的下划线转驼峰配置
configuration:
map-underscore-to-camel-case: true
#另外一种打印语句的方式
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#打印sql时的语句
logging:
level:
com:
acong:
dao: debug
file:
path: d:/logs/demo
2.7 配置文件pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis与spring boot2.x整合包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.20</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
3.效果展示: