开发实例二

tech2022-08-11  123

任务实施

第一步、在项目pom.xml文件中添加依赖

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- druid数据库连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <!--lombok依赖--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--redis依赖配置--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>

第二步、在项目application.yml文件中添加数据库配置、redis配置、jpa配置。

spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=UTC username: root password: 123456 initialSize: 20 minIdle: 50 maxActive: 500 jpa: hibernate: ddl-auto: update show-sql: true redis: host: localhost # Redis服务器地址 database: 0 # Redis数据库索引(默认为0) port: 6379 # Redis服务器连接端口 password: 123456 # Redis服务器连接密码(默认为空) jedis: pool: max-active: 8 # 连接池最大连接数(使用负值表示没有限制) max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制) max-idle: 8 # 连接池中的最大空闲连接 min-idle: 0 # 连接池中的最小空闲连接 timeout: 3000ms # 连接超时时间(毫秒)

第三步、在项目controller控制实体类进行设置。

package com.nmgdz.bigdata.controller; import com.nmgdz.bigdata.entity.User; import com.nmgdz.bigdata.service.RedisService; import com.nmgdz.bigdata.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("user") public class UserController { @Autowired private UserService userService; @Autowired private RedisService redisService; @GetMapping("/gueryBuId") public String gueryById(int id){ //从redis获取key为Id User String userStr=redisService.get(id+""); //判断是否存在 if (userStr==null){ //查询 设置到redis redisService.set(id+"",userService.gueryById(id).toString()); } return userStr; } @PatchMapping("/save") public User saveUser(String name,int age){ return userService.save(new User(name,age)); } }

等等… 学习到处为止。

最新回复(0)