本博客仅供参考,本人实现没有问题。
1、环境
先安装redis、mysql
2、springboot2.0的项目搭建(请自行完成),本人是maven项目,因此只需配置,获取相应的jar包,配置贴出。
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
com.alibaba
druid
1.1.0
org.springframework.boot
spring-boot-starter-redis
1.4.3.RELEASE
com.alibaba
fastjson
1.2.7
3、如果相应的springboot可以正常启动,同时mysql和redis已安装,相应的数据库配置如下(#本人使用了mysql做数据库,redis做缓存和消息队列)。
#默认使用配置
spring:
profiles:
active: dev
#公共配置与profiles选择无关
mybatis:
typeAliasesPackage: com.cn.commodity.entity
mapperLocations: classpath:mapper/*.xml
---
#开发配置
spring:
profiles: dev
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username: root
password: yang156122
driver-class-name: com.mysql.jdbc.Driver
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
#redis配置
redis:
host: 127.0.0.1
port: 6379
password:
pool:
max-active: 100
max-idle: 10
max-wait: 100000
timeout: 0
4、mysql数据库表如下图所示:
到此,环境和数据库都已准备。项目代码如下:
controller层
1、UserController
import com.alibaba.fastjson.JSONObject;
import com.cn.commodity.entity.User;
import com.cn.commodity.service.RedisService;
import com.cn.commodity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@Autowired
private RedisService redisService;
private JSONObject json = new JSONObject();
@RequestMapping("/showUser")
@ResponseBody
public User showUser(HttpServletRequest request){
User user = null;
int userId = Integer.parseInt(request.getParameter("id"));
String result = redisService.get("user");
if(result==null) {
user = this.userService.getUserById(userId);
System.out.println("来自数据库:"+user.getUserName());
redisService.set("user",json.toJSONString(user));
}else {
user = json.parseObject(result, User.class);
System.out.println("来自redis缓存:"+user.getUserName());
}
return user;
}
@RequestMapping("/showListUser")
@ResponseBody
public List showListUser(HttpServletRequest request) {
List userList = null;
String result = redisService.get("userList");
if(result==null){
userList = userService.selectAllUser();
System.out.println("来自数据库:"+userList);
redisService.set("userList",json.toJSONString(userList));
}else {
userList = json.parseArray(result,