首页 > 数据库 >springboot+mybatis+redis+mysql项目搭建,含示例Demo

springboot+mybatis+redis+mysql项目搭建,含示例Demo

时间:2023-02-28 15:11:06浏览次数:66  
标签:return springboot 示例 Demo public dept Integer RespBean id

转载自:https://blog.csdn.net/qq_40772342/article/details/105049322

==========

 

redis在web开发中使用的场景很多,其中缓存是其中一个很重要的使用场景,之所以用作缓存,得益于redis的读写数据,尤其是在读取数据的时候是直接走内存的,这样在高并发访问数据的时候,和查询数据库相比,redis读取数据的高效性、快速性的优势可见一斑

Redis注解概念

在看代码前先看看目录结构

 

 

 

 

 

 


启动类

@SpringBootApplication
@EnableCaching
public class RedisdemoApplication {

public static void main(String[] args) {
SpringApplication.run(RedisdemoApplication.class, args);
}

}

 

application.yml配置

spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/schooldb?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
#redis配置
redis:
host: 127.0.0.1
password: 123456
port: 6379
jedis:
pool:
max-active: 20
max-idle: 8
min-idle: 0
max-wait: 5000
#mybatis的配置
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:mapper/*.xml

 

实体类

public class Dept implements Serializable {
private Integer id;
private String dname;
private String loc;

@Override
public String toString() {
return "Dept{" +
"id=" + id +
", dname='" + dname + '\'' +
", loc='" + loc + '\'' +
'}';
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getDname() {
return dname;
}

public void setDname(String dname) {
this.dname = dname;
}

public String getLoc() {
return loc;
}

public void setLoc(String loc) {
this.loc = loc;
}
}

 

public class RespBean {
private Integer status;
private String msg;
private Object obj;

public RespBean(Integer status, String msg) {
this.status = status;
this.msg = msg;
}

public static final RespBean DELETE_SUCCESS = new RespBean(200,"删除成功");
public static final RespBean DELETE_ERROR = new RespBean(-1,"删除失败");

public static final RespBean ADD_SUCCESS = new RespBean(200,"添加成功");
public static final RespBean ADD_ERROR = new RespBean(-1,"添加失败");

public static final RespBean UPDATE_SUCCESS = new RespBean(200,"更新成功");
public static final RespBean UPDATE_ERROR = new RespBean(-1,"更新失败");

public Integer getStatus() {
return status;
}

public void setStatus(Integer status) {
this.status = status;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public Object getObj() {
return obj;
}

public void setObj(Object obj) {
this.obj = obj;
}

private RespBean(Integer status, String msg, Object obj) {
this.status = status;
this.msg = msg;
this.obj = obj;
}

private RespBean() {
}
}

 

mapper层

@Mapper
public interface DeptMapper {
Integer addDept(Dept dept);
Integer deleteById(Integer id);
Integer updateDeptById(Dept dept);
Dept findAllDept(Integer id);
}

 

service层

public interface DeptService {
Dept addDept(Dept dept);
Integer deleteById(Integer id);
Dept updateDeptById(Dept dept);
Dept findAllDept(Integer id);
}

 

serviceimpl层

@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptMapper deptMapper;

@CachePut(cacheNames = "dept",key = "#result.id")
@Override
public Dept addDept(Dept dept) {
deptMapper.addDept(dept);

return dept;
}

@CacheEvict(cacheNames = "dept")
@Override
public Integer deleteById(Integer id) {
Integer result=deptMapper.deleteById(id);
return result;
}
@CachePut(cacheNames = "dept",key = "#result.id")
@Override
public Dept updateDeptById(Dept dept) {
deptMapper.updateDeptById(dept);
return dept;
}

@Cacheable(cacheNames = "dept",key = "#id")
@Override
public Dept findAllDept(Integer id) {
return deptMapper.findAllDept(id);
}

}

 

controller

@RestController
@RequestMapping("/dept")
public class DeptController {
@Autowired
private DeptService deptService;

@GetMapping("/{id}")
public Object findAll(@PathVariable Integer id){
Dept allDept = deptService.findAllDept(id);
return allDept;
}

/**
* 删除
* @param id
* @return
*/
@DeleteMapping("/{id}")
public RespBean deleteDept(@PathVariable Integer id){
try {
deptService.deleteById(id);
return RespBean.DELETE_SUCCESS;//删除成功
} catch (Exception e) {
e.printStackTrace();
return RespBean.DELETE_ERROR;//删除失败
}
}

/**
* 添加
* @param dept
* @return
*/
@PostMapping("/")
public RespBean addDept(@RequestBody Dept dept){
try {
deptService.addDept(dept);
return RespBean.ADD_SUCCESS;//添加成功
} catch (Exception e) {
e.printStackTrace();
return RespBean.ADD_ERROR;//添加失败
}
}

/**
* 更新
* @param dept
* @return
*/
@PutMapping("/")
public RespBean updateDept(@RequestBody Dept dept){
try {
deptService.updateDeptById(dept);
return RespBean.UPDATE_SUCCESS;//添加成功
} catch (Exception e) {
e.printStackTrace();
return RespBean.UPDATE_ERROR;//添加失败
}

}


}

 

DeptMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.song.mapper.DeptMapper">

<insert id="addDept" keyProperty="id" useGeneratedKeys="true" parameterType="com.song.entity.Dept" >
insert into dept(dname,loc)values (#{dname},#{loc})
</insert>

<delete id="deleteById">
delete from dept where id=#{id}
</delete>

<update id="updateDeptById" parameterType="com.song.entity.Dept">
update dept set dname=#{dname},loc=#{loc} where id=#{id}
</update>

<select id="findAllDept" resultType="com.song.entity.Dept" >
select*from dept where id=#{id}
</select>
</mapper>

 

改变默认jdk序列化器

@Configuration
public class MyRedisConfig {
@Bean(name = "redisTemplate")
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){

RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();

redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(keySerializer());
redisTemplate.setHashKeySerializer(keySerializer());
redisTemplate.setValueSerializer(valueSerializer());
redisTemplate.setHashValueSerializer(valueSerializer());
return redisTemplate;
}

@Primary
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
//缓存配置对象
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();

redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) //设置缓存的默认超时时间:30分钟
.disableCachingNullValues() //如果是空值,不缓存
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer())) //设置key序列化器
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer()))); //设置value序列化器

return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}


private RedisSerializer<String> keySerializer() {
return new StringRedisSerializer();
}

private RedisSerializer<Object> valueSerializer() {
return new GenericJackson2JsonRedisSerializer();
}
}

 

效果

可以打开redis可视化工具,首先没有数据

 

 

使用postman测试

 

 

redis中

 

 

git链接:https://github.com/huangdan92/springbootRedis

标签:return,springboot,示例,Demo,public,dept,Integer,RespBean,id
From: https://www.cnblogs.com/hd92/p/17164339.html

相关文章

  • springboot整合shiro
    1.什么是ShiroShiro是一个基于Java的安全框架,它提供了身份验证、授权、加密和会话管理等安全功能,可以帮助Java应用程序实现安全性。2.根据Shiro的基本使用了解其基本......
  • SpringBoot全局异常封装:AOP增强
    api请求错误返回json,页面请求错误跳转报错页面:自动装配、异常通知两个方法Java异常类错误无法避免,通常由于系统原因造成。如IOError,注意不是IOException,原因可能是......
  • 给WPF示例图形加上方便查看大小的格子之完善版本
    去年10月份,我曾写过一篇"给WPF示例图形加上方便查看大小的格子"的BLOG,这次由于需要,将它完善一下,可以有效地区别100的整数倍逻辑像素(与设备无关像素)单位的显示。显示效......
  • WPF,SilverLight中直线的样式示例
    XAML代码://LineStyle.xaml<ViewboxWidth="600"Height="500"xmlns="​​​http://schemas.microsoft.com/winfx/2006/xaml/presentation​​​"xmlns:x="​​​http:......
  • springboot处理乱码问题原理
    我们在用spring-springmvc时,需要配置一个过滤器 CharacterEncodingFilterCharacterEncodingFilterfilter=newOrderedCharacterEncodingFilter();filter.setEncodin......
  • springboot集成easyexcel(阿里)
    poi比较占用内存。easyexcel性能优化不少,值得一看。pom.xml中添加:<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.1.6</......
  • springboot中json参数映射
    文章目录​​json映射不到实体上​​​​问题分析​​​​解决方案​​​​json映射到String查不到数据​​​​问题分析​​​​解决方案​​​​自动映射入参可以多吗,可以......
  • 转载:pageOffice插件 springboot实现服务器上Word文档在线打开编辑保存
    pageOffice插件springboot实现服务器上Word文档在线打开编辑保存需求:在oa系统上,想实现在线,服务器上doc,docx文档,在web打开,编辑。编辑后,可以再同步保存到服务器端。......
  • Golang如何快速构建一个CLI小工示例
    这篇文章主要为大家介绍了Golang如何快速构建一个CLI小工具详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪如何Golang快速构建一个CLI......
  • java正则匹配demo
    java正则匹配实现1.问题描述根据指定的字段名限制条件,提取出sql语句中的对应字段名并返回。字段名限制条件如下:必须以${开头,}结尾;中间只能包含字母、数字和下划......