1 添加redis支持
在pom.xml中添加
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-redis</artifactId>
- </dependency>
2 redis配置
package com.kaishustory.conf.cache;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.lang.reflect.Method;
@Configuration
@EnableCaching
@SuppressWarnings("rawtypes")
public class RedisCacheConfig extends CachingConfigurerSupport{
@Bean
public KeyGenerator wiselyKeyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@Bean
public CacheManager cacheManager( RedisTemplate redisTemplate) {
return new RedisCacheManager(redisTemplate);
}
@SuppressWarnings("unchecked")
@Bean
public RedisTemplate<String, String> redisTemplate(
RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
3 redis服务器配置
- # REDIS (RedisProperties)
- spring.redis.database= # database name
- spring.redis.host=localhost # server host
- spring.redis.password= # server password
- spring.redis.port=6379 # connection port
- spring.redis.pool.max-idle=8 # pool settings ...
- spring.redis.pool.min-idle=0
- spring.redis.pool.max-active=8
- spring.redis.pool.max-wait=-1
- spring.redis.sentinel.master= # name of Redis server
- spring.redis.sentinel.nodes= # comma-separated list of host:port pairs
4 应用
测试两个实体类
package com.kaishustory.demo.domain; import java.io.Serializable; import java.util.Date; import javax.persistence.Table; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import tk.mybatis.mapper.entity.IDynamicTableName; @SuppressWarnings("serial") @Table(name = "ks_demo") public class DemoDomain implements IDynamicTableName, Serializable { private int id; @JsonProperty("uid") private int userid; private String openid; private String unionid; private String nickname; private String birthday; private String sex; private int status; @JsonIgnore private Date createtime; @Transient // 非表字段,字段名称无所谓 @JsonIgnore private String dynamicTableName123; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getUnionid() { return unionid; } public void setUnionid(String unionid) { this.unionid = unionid; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } @Override @JsonIgnore public String getDynamicTableName() { return dynamicTableName123; } public void setDynamicTableName(String dynamicTableName) { this.dynamicTableName123 = dynamicTableName; } }
使用演示
package com.kaishustory.demo.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.kaishustory.base.service.BaseService; import com.kaishustory.demo.domain.DemoDomain; import com.kaishustory.demo.mapper.DemoMapper; @Service public class DemoService extends BaseService<DemoDomain>{ @Autowired DemoMapper demomapper; @Cacheable(value = "usercache",keyGenerator = "wiselyKeyGenerator") public PageInfo<DemoDomain> selectByPage(int pageNum, int pageSize){ //获取第1页,10条内容,默认查询总数count PageHelper.startPage(pageNum, pageSize); List<DemoDomain> demoList = demomapper.selectAll(); //用PageInfo对结果进行包装 PageInfo<DemoDomain> page = new PageInfo<DemoDomain>(demoList); //测试PageInfo全部属性 //PageInfo包含了非常全面的分页属性 System.err.println("PageNum:"+page.getPageNum()); System.err.println("PageSize"+page.getPageSize()); System.err.println(page.getStartRow()); System.err.println(page.getEndRow()); System.err.println(page.getTotal()); System.err.println(page.getPages()); System.err.println(page.getFirstPage()); System.err.println(page.getLastPage()); System.err.println(page.isIsFirstPage()); System.err.println(page.isIsLastPage()); System.err.println(page.isHasPreviousPage()); System.err.println(page.isHasNextPage()); return page; } }
package com.kaishustory.demo.controller; import java.util.Date; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; 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.RestController; import com.github.pagehelper.PageInfo; import com.kaishustory.commons.bean.PageBean; import com.kaishustory.commons.bean.RespCodeConstants; import com.kaishustory.commons.bean.RespResult; import com.kaishustory.demo.domain.DemoDomain; import com.kaishustory.demo.service.DemoService; import com.kaishustory.demo.vo.input.InputVo; @RestController @RequestMapping("/demoservice") public class DemoController { @Autowired DemoService demoservice; // 分页测试接口 @RequestMapping(value="/listByPage",method=RequestMethod.GET) public RespResult listByPage( @RequestParam(name="page_no",defaultValue="1") int pageNum, @RequestParam(name="page_size",defaultValue="15") int pageSize){ PageInfo<DemoDomain> pageInfo = demoservice.selectByPage(pageNum,pageSize); // 构造返回分页PageBean return new RespResult(RespCodeConstants.SUCCESS, new PageBean(pageInfo)); } }
结果展示: