文件路径

              

添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>wonder</groupId>
<artifactId>skyRainbow</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <dependencies> <!--spring boot 的依赖 START-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--spring boot 的依赖 END--> <!--mybatis 的依赖 START-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!--mybatis 的依赖 END--> <!--mysql 的依赖 START-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--mysql 的依赖 END--> <!--jsp 的依赖 START-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--jsp 的依赖 END--> <!--swagger 的依赖 START-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency> <dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
<!--swagger 的依赖 END--> <!--c3p0 的依赖 START-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!--c3p0 的依赖 END--> <!--redis 的依赖 START-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<!--redis 的依赖 END--> </dependencies> <build>
<!--配置文件读取路径-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources> <plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

添加c3p0数据源文件和swagger的启动文件

package lf.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary; import javax.sql.DataSource; @Configuration
public class DatasourceConfiguration { @Bean(name = "dataSource")
@Qualifier(value = "dataSource")
@Primary
@ConfigurationProperties(prefix = "c3p0")
public DataSource dataSource()
{
return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build();
}
}
package lf.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex; @Configuration
@EnableSwagger2
public class SwaggerConfig { @Bean
public Docket api_lf(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("api_lf")
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(false)
.pathMapping("/")
.select()
.paths(or(regex("/lf/.*")))
.build()
.apiInfo(apiInfo()); } /**
* 构建api文档详细信息
*/
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo(
"甘雨路 API",// 标题
"API 描述说明",//描述
"1.0",//版本
"NO terms of service",
"lf@qq.com",// 创建人
"The Apache License, Version 2.0",
"http://www.apache.org/licenses/LICENSE-2.0.html"
);
return apiInfo;
} }

添加控制层

package lf.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lf.entity.BsdUser;
import lf.service.BsdUserSerive;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.Resource;
import java.util.Date; @Controller
@RequestMapping(value="${modulePath}/page")
@Api(description = "页面跳转控制器")
public class PageController {
@Resource
private BsdUserSerive userSerive;
/**
* 进入公司主页
*/
@RequestMapping(value = "/company",method = RequestMethod.GET)
public String gotoCompanyPage(Model model,@RequestParam @ApiParam("用户id") Long id){
BsdUser user = userSerive.getUserById(id);
model.addAttribute("time",new Date());
model.addAttribute("loginName",user.getName());
return "main";
} }
package lf.controller;

import io.swagger.annotations.*;
import lf.entity.BsdUser;
import lf.service.BsdUserSerive;
import lf.utils.CommonDTO;
import lf.utils.CommonUtil;
import lf.utils.redis.RedisUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; @Api(description = "用户控制器")//swagger注解用于类
@Controller // 控制器注解
@RequestMapping(value="${modulePath}/user")
public class UserController { @Resource
private RedisUtil redisUtil; @Resource
private BsdUserSerive userSerive; @ResponseBody
@RequestMapping(value = "/info",method = RequestMethod.GET)
public CommonDTO<BsdUser> getUserbyId(@RequestParam @ApiParam("用户id") Long id){
CommonDTO<BsdUser> detailDTO = new CommonDTO<>(0,1);
try {
BsdUser user = null;
// 从缓存中获取数据
user = (BsdUser)redisUtil.get(CommonUtil.USER_INFO_KEY + id);
if (user == null){
user = userSerive.getUserById(id);
// 将数据存入缓存
redisUtil.set(CommonUtil.USER_INFO_KEY + id,user);
System.out.println("从数据库获取的数据");
}else {
System.out.println("从缓存中获取数据");
} //BsdUser user = userSerive.getUserById(id);
detailDTO.setData(user);
} catch (Exception e) {
e.printStackTrace();
detailDTO.setStatus(1);
detailDTO.setCode(400);
detailDTO.setMsg("获取用户信息异常:"+e.getMessage()); } return detailDTO;
} }

添加实体类

package lf.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date; @ApiModel(description = "用户实体")
public class BsdUser implements Serializable {
@ApiModelProperty("主键")
private Long id;
@ApiModelProperty("组织id")
private Long orgId;
@ApiModelProperty("用户类型(0,品牌商1,服务商2,零售商,3客服)")
private Integer userType;
@ApiModelProperty("登录名")
private String loginName;
@ApiModelProperty("电话")
private String phone;
@ApiModelProperty("姓名")
private String name;
@ApiModelProperty("简称")
private String shortName;
@ApiModelProperty("密码")
private String password;
@ApiModelProperty("联系人")
private String contactUserName;
@ApiModelProperty("地址")
private String address;
@ApiModelProperty("经度")
private BigDecimal longitude;
@ApiModelProperty("纬度")
private BigDecimal latitude;
@ApiModelProperty("级别(0,普通会员,1,一级会员,2,二级会员,3三级会员,4,四级会员,5,五级会员)")
private Integer level;
@ApiModelProperty("状态(0,无效,1有效,2未审核,3审核未通过)")
private Integer state;
@ApiModelProperty("银行卡")
private String bankCard;
@ApiModelProperty("总积分")
private Long totalPoints;
@ApiModelProperty("上级组织id")
private Long superiorId;
@ApiModelProperty("创建人id")
private Long createdBy;
@ApiModelProperty("最后更新人")
private Long lastUpdatedBy;
@ApiModelProperty("创建日期")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createdDate;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
@ApiModelProperty("最后更新日期")
private Date lastUpdatedDate;
@ApiModelProperty("软删除标志")
private Integer removeFlag;
@ApiModelProperty("图片地址")
private String imgUrl;
@ApiModelProperty("消费总金额")
private BigDecimal totalPaymentAmount;
@ApiModelProperty("佣金")
private BigDecimal commission;
@ApiModelProperty("运费")
private BigDecimal freight;
@ApiModelProperty("编号")
private String code;
@ApiModelProperty("已经支付定金")
private Long depositPaid;
@ApiModelProperty("注册信息附件信息传")
private String registerAttachmentUrl;
@ApiModelProperty("支付密码")
private String payPassWord;
@ApiModelProperty("钱包余额")
private BigDecimal balance;
@ApiModelProperty("现金卷余额")
private BigDecimal cashRoll; private static final long serialVersionUID = 1L; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public Long getOrgId() {
return orgId;
} public void setOrgId(Long orgId) {
this.orgId = orgId;
} public Integer getUserType() {
return userType;
} public void setUserType(Integer userType) {
this.userType = userType;
} public String getCode() {
return code;
} public void setCode(String code) {
this.code = code == null ? null : code.trim();
} public String getLoginName() {
return loginName;
} public void setLoginName(String loginName) {
this.loginName = loginName == null ? null : loginName.trim();
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
} public String getShortName() {
return shortName;
} public void setShortName(String shortName) {
this.shortName = shortName == null ? null : shortName.trim();
} public String getName() {
return name;
} public void setName(String name) {
this.name = name == null ? null : name.trim();
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password == null ? null : password.trim();
} public String getContactUserName() {
return contactUserName;
} public void setContactUserName(String contactUserName) {
this.contactUserName = contactUserName == null ? null : contactUserName.trim();
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address == null ? null : address.trim();
} public BigDecimal getLongitude() {
return longitude;
} public void setLongitude(BigDecimal longitude) {
this.longitude = longitude;
} public String getRegisterAttachmentUrl() {
return registerAttachmentUrl;
} public void setRegisterAttachmentUrl(String registerAttachmentUrl) {
this.registerAttachmentUrl = registerAttachmentUrl == null ? null : registerAttachmentUrl.trim();
} public BigDecimal getLatitude() {
return latitude;
} public void setLatitude(BigDecimal latitude) {
this.latitude = latitude;
} public Integer getLevel() {
return level;
} public void setLevel(Integer level) {
this.level = level;
} public String getImgUrl() {
return imgUrl;
} public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl == null ? null : imgUrl.trim();
} public Integer getState() {
return state;
} public void setState(Integer state) {
this.state = state;
} public String getBankCard() {
return bankCard;
} public void setBankCard(String bankCard) {
this.bankCard = bankCard == null ? null : bankCard.trim();
} public BigDecimal getTotalPaymentAmount() {
return totalPaymentAmount;
} public void setTotalPaymentAmount(BigDecimal totalPaymentAmount) {
this.totalPaymentAmount = totalPaymentAmount;
} public Long getTotalPoints() {
return totalPoints;
} public void setTotalPoints(Long totalPoints) {
this.totalPoints = totalPoints;
} public Long getSuperiorId() {
return superiorId;
} public void setSuperiorId(Long superiorId) {
this.superiorId = superiorId;
} public BigDecimal getCommission() {
return commission;
} public void setCommission(BigDecimal commission) {
this.commission = commission;
} public BigDecimal getFreight() {
return freight;
} public void setFreight(BigDecimal freight) {
this.freight = freight;
} public Long getDepositPaid() {
return depositPaid;
} public void setDepositPaid(Long depositPaid) {
this.depositPaid = depositPaid;
} public String getPayPassWord() {
return payPassWord;
} public void setPayPassWord(String payPassWord) {
this.payPassWord = payPassWord == null ? null : payPassWord.trim();
} public BigDecimal getBalance() {
return balance;
} public void setBalance(BigDecimal balance) {
this.balance = balance;
} public BigDecimal getCashRoll() {
return cashRoll;
} public void setCashRoll(BigDecimal cashRoll) {
this.cashRoll = cashRoll;
} public Long getCreatedBy() {
return createdBy;
} public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
} public Date getCreatedDate() {
return createdDate;
} public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
} public Long getLastUpdatedBy() {
return lastUpdatedBy;
} public void setLastUpdatedBy(Long lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
} public Date getLastUpdatedDate() {
return lastUpdatedDate;
} public void setLastUpdatedDate(Date lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
} public Integer getRemoveFlag() {
return removeFlag;
} public void setRemoveFlag(Integer removeFlag) {
this.removeFlag = removeFlag;
}
}

添加mapper层

package lf.mapper;

import lf.entity.BsdUser;
import org.mapstruct.Mapper; import java.math.BigDecimal;
import java.util.List;
import java.util.Map; public interface BsdUserMapper{ /**
* 根据用户id获取用户信息
* @param id
* @return
*/
public BsdUser getUserById(Long id); }

添加mapper的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="lf.mapper.BsdUserMapper">
<resultMap id="BsdUserResultMap" type="lf.entity.BsdUser">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="org_id" jdbcType="BIGINT" property="orgId" />
<result column="user_type" jdbcType="INTEGER" property="userType" />
<result column="code" jdbcType="VARCHAR" property="code" />
<result column="login_name" jdbcType="VARCHAR" property="loginName" />
<result column="phone" jdbcType="VARCHAR" property="phone" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="short_name" property="shortName" jdbcType="VARCHAR" />
<result column="register_attachment_url" property="registerAttachmentUrl" jdbcType="VARCHAR" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="contact_user_name" jdbcType="VARCHAR" property="contactUserName" />
<result column="address" jdbcType="VARCHAR" property="address" />
<result column="longitude" jdbcType="DECIMAL" property="longitude" />
<result column="latitude" jdbcType="DECIMAL" property="latitude" />
<result column="level" jdbcType="INTEGER" property="level" />
<result column="img_url" jdbcType="VARCHAR" property="imgUrl" />
<result column="state" jdbcType="INTEGER" property="state" />
<result column="bank_card" jdbcType="VARCHAR" property="bankCard" />
<result column="total_payment_amount" jdbcType="DECIMAL" property="totalPaymentAmount" />
<result column="commission" jdbcType="DECIMAL" property="commission" />
<result column="freight" jdbcType="DECIMAL" property="freight" />
<result column="total_points" jdbcType="BIGINT" property="totalPoints" />
<result column="superior_id" jdbcType="BIGINT" property="superiorId" />
<result column="created_by" jdbcType="BIGINT" property="createdBy" />
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate" />
<result column="last_updated_by" jdbcType="BIGINT" property="lastUpdatedBy" />
<result column="last_updated_date" jdbcType="TIMESTAMP" property="lastUpdatedDate" />
<result column="remove_flag" jdbcType="INTEGER" property="removeFlag" />
<result column="deposit_paid" jdbcType="DECIMAL" property="depositPaid" />
<result column="pay_pass_word" jdbcType="VARCHAR" property="payPassWord" />
<result column="balance" jdbcType="DECIMAL" property="balance" />
<result column="cash_roll" jdbcType="DECIMAL" property="cashRoll" />
</resultMap>
<sql id="BsdUser_Column_List">
id, org_id, user_type, code, login_name, phone, name,short_name,register_attachment_url,password, contact_user_name,
address, longitude, latitude, level, img_url, state, bank_card, total_payment_amount,commission,freight,
total_points, superior_id, created_by, created_date, last_updated_by, last_updated_date,
remove_flag, deposit_paid, pay_pass_word, balance, cash_roll
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BsdUserResultMap">
select
<include refid="BsdUser_Column_List" />
from bsd_user
where id = #{id}
</select> <select id="getUserById" parameterType="java.lang.Long" resultMap="BsdUserResultMap">
select
<include refid="BsdUser_Column_List" />
from bsd_user
where id = #{id}
</select> </mapper>

添加service层和实现类

package lf.service;

import lf.entity.BsdUser;

public interface BsdUserSerive {
/**
* 根据用户id获取用户
* @param id
* @return
*/
public BsdUser getUserById(Long id);
}
package lf.service.impl;

import lf.entity.BsdUser;
import lf.mapper.BsdUserMapper;
import lf.service.BsdUserSerive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service
public class BsdUserSeriveImpl implements BsdUserSerive{ @Autowired
private BsdUserMapper userMapper;
/**
* 根据用户id获取用户信息
* @param id
* @return
*/
@Override
public BsdUser getUserById(Long id) {
return userMapper.getUserById(id);
}
}

添加工具类

package lf.utils.redis;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*; import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit; /**
* redis cache 工具类
*
*/
public final class RedisUtil {
private Logger logger = Logger.getLogger(RedisUtil.class);
private RedisTemplate<Serializable, Object> redisTemplate;
private String redisIp; /**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
} /**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
} /**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
} /**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
} /**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
// LogUtil.error("-----------------------------redisIp"+redisIp);
// System.err.println("-----------------------------redisIp"+redisIp);
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
} /**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
// LogUtil.error("-----------------------------redisIp"+redisIp);
// System.err.println("-----------------------------redisIp" + redisIp);
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
// LogUtil.error("-----------------------------redisIp"+redisIp);
// System.err.println("-----------------------------redisIp"+redisIp);
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
} public String getRedisIp() {
return redisIp;
} public void setRedisIp(String redisIp) {
this.redisIp = redisIp;
} /**
* 设置新值,同时返回旧值
* @param lockKey
* @param stringOfLockExpireTime
* @return
*/
public String getSet(final String lockKey, final String stringOfLockExpireTime) {
String result = redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
byte[] bytes = redisConnection.getSet(lockKey.getBytes(), stringOfLockExpireTime.getBytes());
if(bytes != null) {
return new String(bytes);
}
return null;
}
});
return result;
} /**
* 如果不存在key则插入
* @param lockKey
* @param stringOfLockExpireTime
* @return true 插入成功, false 插入失败
*/
public boolean setnx(final String lockKey, final String stringOfLockExpireTime) {
return redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
return redisConnection.setNX(lockKey.getBytes(), stringOfLockExpireTime.getBytes());
}
});
} /**
* setnx 和 getSet方式插入的数据,调用此方法获取
* @param key
* @return
*/
public String getInExecute(final String key) {
String result = redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
byte[] bytes = redisConnection.get(key.getBytes());
if (bytes == null) {
return null;
} else {
return new String(bytes);
}
}
});
return result;
} /**
* 将缓存保存在map集合中
* @param redisKey
* @param mapKey
* @param mapValue
* @return
*/
public boolean putInMap(final String redisKey, String mapKey, Object mapValue) {
boolean result = false;
try {
HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
operations.put(redisKey, mapKey, mapValue);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} public Object getOneFromMap(final String redisKey, String mapKey) {
HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
return operations.get(redisKey, mapKey);
} public Object getAllFromMap(final String redisKey) {
HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
return operations.values(redisKey);
} public void removeFromMap(final String redisKey, Object obj) {
HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
operations.delete(redisKey, obj);
} public boolean setList(final String key, Object value) {
boolean result = false;
try {
ListOperations<Serializable, Object> listOperations = redisTemplate.opsForList();
listOperations.leftPush(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} public Object getList(final String key) {
ListOperations<Serializable, Object> listOperations = redisTemplate.opsForList();
return listOperations.range(key,0,listOperations.size(key));
} }
package lf.utils;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import java.util.Map; /**
* 详情Dto
* @param <T>
*/
@ApiModel(description = "详情DTO")
public class CommonDTO<T>{ @ApiModelProperty(value = "提示信息")
private String msg; @ApiModelProperty(value = "0 代表无错误 1代表有错误")
private Integer status; @ApiModelProperty(value = "总记录")
private Integer total; @ApiModelProperty(value = "业务数据")
private T data; @ApiModelProperty(value = "200 代表无错误 400代表有错误--->加入这个字段是原生需求")
private Integer code; @ApiModelProperty(value = "当前页码")
private Integer pageNo = 1; @ApiModelProperty(value = "当前页码,默认:10")
private Integer pageSize = Integer.valueOf(10); // 页面大小,设置为“-1”表示不进行分页(分页无效) @ApiModelProperty(value = "总记录数")
private long totalSize;// 总记录数,设置为“-1”表示不查询总数 private Map<String,Object> DataMap; public CommonDTO(Integer status) {
if (status == 0){
this.status = status;
this.code = 200;
this.msg = "操作成功";
}
this.data = null;
} public CommonDTO(Integer status, Integer total) {
if (status == 0){
this.status = status;
this.code = 200;
this.msg = "操作成功";
}
this.data = null;
this.total = total;
} public Map<String, Object> getDataMap() {
return DataMap;
} public void setDataMap(Map<String, Object> dataMap) {
DataMap = dataMap;
} public Integer getCode() {return code;} public void setCode(Integer code) {this.code = code;} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
} public Integer getStatus() {
return status;
} public void setStatus(Integer status) {
this.status = status;
} public Integer getTotal() {
return total;
} public void setTotal(Integer total) {
this.total = total;
} public T getData() {
return data;
} public void setData(T data) {
this.data = data;
} public Integer getPageNo() {
return (pageNo!=null&&pageNo>0)?pageNo:-1;
} public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
} public Integer getPageSize() {
return (pageSize!=null&&pageSize>0)?pageSize:10;
} public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
} /**
* 获取设置总数
* @return
*/
public long getTotalSize() {
return totalSize;
} /**
* 设置数据总数
* @param count
*/
public void setTotalSize(long totalSize) {
this.totalSize = totalSize;
if (pageSize >= totalSize){
pageNo = 1;
}
} @Override
public String toString() {
return "CommonDTO{" +
"msg='" + msg + '\'' +
", status=" + status +
", total=" + total +
", data=" + data +
'}';
}
}
package lf.utils;

import io.swagger.annotations.Api;

@Api(value = "常量类")
public class CommonUtil { public static final String USER_INFO_KEY = "USER_INFO_KEY";
}

添加是springboot启动文件

package lf;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource; @SpringBootApplication
@MapperScan("lf.mapper") // mapper层的路径
@PropertySource({"classpath:mybatis.properties",
"classpath:c3p0.properties",
"classpath:redis.properties"})// 读取.properties 文件路径
@ImportResource({"classpath:config/applicationContext-jedis.xml"})// 读取文件路径
public class SkyRainbowApplication { public static void main(String[] args) {
/**
* Spring boot 程序入口
*/
SpringApplication.run(SkyRainbowApplication.class,args);
}
}

添加jsp 文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<body> <h1>欢迎登陆甘雨路主页</h1>
<div>登陆时间:${time}</div>
<div>登陆人:${loginName}</div> </body>
</html>

添加redis配置文件和mybatis配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"> <!-- redis配置开始 -->
<!-- 配置 JedisPoolConfig 实例 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.pool.maxTotal}" />
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="minIdle" value="${redis.pool.minIdle}" />
<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
<property name="testOnReturn" value="${redis.pool.testOnReturn}" />
<property name="testWhileIdle" value="${redis.pool.testWhileIdle}" />
</bean> <!-- 配置JedisConnectionFactory -->
<bean id="connectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
<property name="poolConfig" ref="poolConfig" />
<property name="port" value="${redis.port}" />
<property name="hostName" value="${redis.ip}" />
<property name="password" value="${redis.pass}" />
<property name="timeout" value="5000" ></property>
</bean > <!-- 配置RedisTemplate -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
<property name="connectionFactory" ref="connectionFactory" />
<property name="keySerializer" >
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer" >
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
</bean > <!-- 配置RedisUtil bean -->
<bean id="redisUtil" class="lf.utils.redis.RedisUtil" >
<property name="redisTemplate"><ref bean= "redisTemplate"/></property>
<property name="redisIp" value="${redis.ip}" />
</bean> </beans>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>

添加application.properties 文件

# 页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/jsp/
# 响应页面默认后缀
spring.mvc.view.suffix=.jsp #swagger
modulePath=/lf

添加c3p0.properties文件

# c3p0 配置
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/bsdmxm?useUnicode=true&characterEncoding=utf8
c3p0.user=lf
c3p0.password=lf
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.minPoolSize=2
c3p0.maxPoolSize=10
c3p0.maxIdleTime=1800000
c3p0.acquireIncrement=3
c3p0.maxStatements=1000
c3p0.initialPoolSize=3
c3p0.idleConnectionTestPeriod=60
c3p0.acquireRetryAttempts=30
c3p0.acquireRetryDelay=1000
c3p0.breakAfterAcquireFailure=false
c3p0.testConnectionOnCheckout=false

添加mybatis.properties文件

#mybatis 配置
# mybatis xml配置文件的路径
mybatis.config-locations=classpath:config/mybatis-config.xml
# mybatis xml文件的路径
mybatis.mapper-locations=classpath:lf/mapper/xml/*.xml
# 实体类的路径
mybatis.type-aliases-package=lf.entity

添加redis.properties文件

#Redis 配置
#最大连接数
redis.pool.maxTotal=1024
#最大空闲连接数
redis.pool.maxIdle=100
#最小空闲连接数, 默认0
redis.pool.minIdle=10
#获取连接时的最大等待毫秒数
redis.pool.maxWaitMillis=3000
#在获取连接的时候检查有效性, 默认false
redis.pool.testOnBorrow=true
#在return给pool时,是否提前进行validate操作
redis.pool.testOnReturn=true
#在空闲时检查有效性, 默认false
redis.pool.testWhileIdle=true
#IP
redis.ip=localhost
#Port
redis.port=6379
#密码(默认为空)
redis.pass=

启动程序,在浏览器上输入 http://localhost:8080/lf/user/info?id=51,控制台打印如下

再次刷新页面,数据直接从缓存中获取,控制台打印如下

Spring boot 、swagger、c3p0、mybatis和redis 整合的更多相关文章

  1. Spring Boot 中使用 MyBatis 整合 Druid 多数据源

    2017 年 10 月 20 日   Spring Boot 中使用 MyBatis 整合 Druid 多数据源 本文将讲述 spring boot + mybatis + druid 多数据源配置方 ...

  2. Spring Boot入门系列(十七)整合Mybatis,创建自定义mapper 实现多表关联查询!

    之前讲了Springboot整合Mybatis,介绍了如何自动生成pojo实体类.mapper类和对应的mapper.xml 文件,并实现最基本的增删改查功能.mybatis 插件自动生成的mappe ...

  3. Spring Boot:实现MyBatis分页

    综合概述 想必大家都有过这样的体验,在使用Mybatis时,最头痛的就是写分页了,需要先写一个查询count的select语句,然后再写一个真正分页查询的语句,当查询条件多了之后,会发现真的不想花双倍 ...

  4. Spring Boot:实现MyBatis动态数据源

    综合概述 在很多具体应用场景中,我们需要用到动态数据源的情况,比如多租户的场景,系统登录时需要根据用户信息切换到用户对应的数据库.又比如业务A要访问A数据库,业务B要访问B数据库等,都可以使用动态数据 ...

  5. Spring Boot:实现MyBatis动态创建表

    综合概述 在有些应用场景中,我们会有需要动态创建和操作表的需求.比如因为单表数据存储量太大而采取分表存储的情况,又或者是按日期生成日志表存储系统日志等等.这个时候就需要我们动态的生成和操作数据库表了. ...

  6. Spring Boot 2.x 基础案例:整合Dubbo 2.7.3+Nacos1.1.3(配置中心)

    本文原创首发于公众号:Java技术干货 1.概述 本文将Nacos作为配置中心,实现配置外部化,动态更新.这样做的优点:不需要重启应用,便可以动态更新应用里的配置信息.在如今流行的微服务应用下,将应用 ...

  7. 阿里P7级教你如何在Spring Boot应用程序中使用Redis

    在Spring Boot应用程序中使用Redis缓存的步骤: 1.要获得Redis连接,我们可以使用Lettuce或Jedis客户端库,Spring Boot 2.0启动程序spring-boot-s ...

  8. Spring Boot 2.x 缓存应用 Redis注解与非注解方式入门教程

    Redis 在 Spring Boot 2.x 中相比 1.5.x 版本,有一些改变.redis 默认链接池,1.5.x 使用了 jedis,而2.x 使用了 lettuce Redis 接入 Spr ...

  9. Spring Boot教程(三十七)整合MyBatis

    Spring中整合MyBatis就不多说了,最近大量使用Spring Boot,因此整理一下Spring Boot中整合MyBatis的步骤.搜了一下Spring Boot整合MyBatis的文章,方 ...

随机推荐

  1. SharpNodeSettings项目,可配置的数据采集,统一的工业数据网关,OPC UA服务器开发,PLC数据发布到自身内存,redis,opc ua,以及数据可视化开发

    本项目隶属于 HslCommunication 项目的SDK套件,如果不清楚HslCommunication组件的话,可以先了解那个项目,源代码地址:https://github.com/dathli ...

  2. vim 编辑 windows下的文本时出现乱码, 修改配置后 已解决

    最近用VIM 查看一个 WINDOWS下的文本,打开以后发现出现乱码,具体如上图. 最后在网上找到了一个解决方法: 原文地址: https://www.zhihu.com/question/22363 ...

  3. 揭密FutureTask

    Future是我们在使用java实现异步时最常用到的一个类,我们可以向线程池提交一个Callable,并通过future对象获取执行结果.本篇文章主要讲述了JUC中FutureTask中的一些实现原理 ...

  4. 0302 IT行业就业与软件工程

    阅读以下文章 http://www.thea.cn/news/terminal/9/9389.html http://www.shzhidao.cn/system/2015/09/22/0102610 ...

  5. yarn import 使用package-lock.json

    yarn 1.7(目前最新的版本)支持npm 的package-lock.json 了 环境准备 安装更新yarn sudo npm install -g yarn 查看版本 yarn version ...

  6. android adb端口被占用解决方法

    1.输入adb devices命令 C:\Users\Nick>adb devices List of devices attached adb server version (31) does ...

  7. moodle搭建相关的笔记

    关于moodle内网外网访问问题的解决方案(转) http://blog.chinaunix.net/uid-656828-id-3106027.html

  8. The type org.springframework.context.support.AbstractApplicationContext cannot be resolved

    在 myeclipse中,使用 jdk6和7,并使用 spring-framework-5.0.2.RELEASE 时,编写代码: import org.springframework.context ...

  9. MPEG2-TS音视频同步原理

    一.引言MPEG2系统用于视音频同步以及系统时钟恢复的时间标签分别在ES,PES和TS这3个层次中.  在TS 层, TS头信息包含了节目时钟参考PCR(Program Clock Reference ...

  10. 调用WebAPI接口地址返回序列化的JSON对象中的属性都加了个k__BackingField关键字的解决办法

    1.问题现象: 2.造成此问题的原因是返回的结果对象实体上面加了个可序列号特效 [Serializable].去掉就可以了. 3.解决后的效果: