废话少说,上代码,结合代码讲解:
一、创建maven工程:导入依赖:
<packaging>war</packaging>
<!--修改jdk的版本-->
<properties>
<java.version>1.8</java.version>
</properties> <!-- Add typical dependencies for a web application -->
<dependencies>
<!--Eureka客户端-->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--进行热部署:开启开发者模式-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!--jstl标签-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--配置访问jsp的依赖,这里用不到-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency> <!--mybatis-,这里用不到->
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency> <!-- mybatis分页组件 ,这里用不到-->
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency> <!--<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>--> <!--远程调用,这里用不到, https://mvnrepository.com/artifact/io.github.openfeign/feign-core -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>10.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.20</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency> <dependency>
<groupId>com.joyoung.cloud</groupId>
<artifactId>cloud-common</artifactId>
<version>2.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.1.4.RELEASE</version>
</dependency> </dependencies> <!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!--热部署配置-->
<!--fork : 如果没有该项配置,肯定devtools不会起作用,即应用不会restart -->
<fork>true</fork>
</configuration>
</plugin> </plugins>
</build> 二、配置文件:这里配置文件设置一个也可以,合并后将Redis的配置放在application.yml文件中 application.yml:
#配置后台admin的端口号
server:
port: 8999
#给后台admin模块设置名字
spring:
application:
name: hbuy-admin
#配置访问页面路径的前后缀
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
#将后台模块注册到注册中心
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10010/eureka
#日志的配置
logging:
level:
org:
springframework: error
com:
java:
admin:
mapper: DEBUG
application.properties:
#设置服务器端口号
server.port=8081
#设置数据库连接四大参数
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/jycloud?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=123456
#配置页面跳转
spring.application.name=hbuy-admin
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
#配置注册中心,将此模块注册到注册中心,这里用不到
eureka.client.service-url.defaultZone=http://127.0.0.1:10010/eureka #分页插件
pagehelper.helper-dialect=mysql
pagehelper.params=count=countSql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true mybatis.mapper-locations=classpath:mapper/*.xml spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=root #根据需要
# Redis数据库索引(默认为0)
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
三、启动类:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient; /**
* admin模块的启动类
@EnableEurekaClient
@MapperScan(basePackages = "com.java.admin.mapper")这里如果不使用注册中心,注册中心的注解和依赖、配置都可以去掉
*/ @SpringBootApplication(scanBasePackages = "com.java.admin")
@EnableEurekaClient
@MapperScan(basePackages = "com.java.admin.mapper")
public class AdminStart {
public static void main(String[] args) {
SpringApplication.run(AdminStart.class);
}
}
四、创建实体类-缓存类,SysCach
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* @ClassName: SysCach
* @Description:
* @Version: v1.0.0
* @Author: Fu Hao
* @Date: 2019/12/11 0011 下午 8:21
* Modification History:
* Date Author Version Description
* -------------------------------------------------------------
* 2019/12/11 0011 Fu v1.0.0 创建
*/
@Data
@Accessors(chain = true)
public class SysCach implements Serializable {
/*相当于java类的身份证。主要用于版本控制。
serialVersionUID作用是序列化时保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。
有两种生成方式:
一个是默认的1L,比如:private static final long serialVersionUID = 1L;
一个是根据类名、接口名、成员方法及属性等来生成一个64位的哈希字段,比如:
private static final long serialVersionUID = xxxxL; */
private static final long serialVersionUID = -1119517352037523860L; /**缓存对用的key**/
private String key;
/**缓存对用的value**/
private String value;
/**缓存的过期时间**/
private Long outOfTime;
} 五、统一返回数据格式:RestRes
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo; /**
* @ClassName: RestRes
* @Description: 响应格式化数据
* @Version: v1.0.0
* @Author: Fu Hao
* @Date: 2019/12/11 0011 下午 7:55
* Modification History:
* Date Author Version Description
* -------------------------------------------------------------
* 2019/12/11 0011 Fu v1.0.0 创建
*/
public class RestRes { public static JSONObject table(PageInfo pageInfo) {
JSONObject jsonObject = new JSONObject();
jsonObject.clear();
jsonObject.put("content", pageInfo.getList());
jsonObject.put("totalElements", pageInfo.getTotal());
return jsonObject;
} }
六、Controller层 :CacheController
import com.github.pagehelper.PageInfo;
import com.java.admin.constants.RestRes;
import com.java.admin.service.CacheService;
import com.joyoung.cloud.security.common.entity.admin.SysCach;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*; /**
* @ClassName: CacheController
* @Description: 缓存管理接口
* @Version: v1.0.0
* @Author: Fu Hao
* @Date: 2019/12/11 0011 下午 7:43
* Modification History:
* Date Author Version Description
* -------------------------------------------------------------
* 2019/12/11 0011 Fu v1.0.0 创建
*/
@Api
@RestController
@RequestMapping("/cache")
public class CacheController { @Autowired
private CacheService cacheService; /***
* @Description 清空缓存
* @author Fu Hao on 2019/12/11 0011 下午 7:49
* @param data description
* @return
**/
@CacheEvict(allEntries = true,value = "cloud-admin")
@Delete("/clear")
public int clearCache(){
return 1;
} /***
* @Description 分页查询
* @author Fu Hao on 2019/12/11 0011 下午 8:43
* @param data description
* @return
**/
@ApiOperation(value = "分页查询")
@GetMapping("")
public Object page(String pattern,Integer page, Integer size){
PageInfo pageInfo=cacheService.list(pattern,page,size);
return RestRes.table(pageInfo);
} /***
* @Description 物理删除
* @author Fu Hao on 2019/12/11 0011 下午 8:45
* @param data description
* @return
**/
@ApiOperation(value = "删除")
@DeleteMapping("/remove/{key}")
public Object remove(@PathVariable String key){
cacheService.remove(key);
return 1;
} /***
* @Description 通过id获取缓存
* @author Fu Hao on 2019/12/11 0011 下午 9:16
* @param data description
* @return
**/
@ApiOperation(value = "查询一条记录")
@GetMapping("/get/{key}")
public Object get(@PathVariable String key){
return cacheService.get(key);
} /***
* @Description 新增一条缓存记录
* @author Fu Hao on 2019/12/11 0011 下午 9:24
* @param data description
* @return
**/
@ApiOperation(value = "新增一条信息")
@PostMapping("/add")
public void add(SysCach sysCach){
cacheService.add(sysCach);
} } 七、service层:CacheService
import com.github.pagehelper.PageInfo;
import com.joyoung.cloud.security.common.entity.admin.SysCach; /**
* @ClassName: CacheService
* @Description:
* @Version: v1.0.0
* @Author: Fu Hao
* @Date: 2019/12/11 0011 下午 7:53
* Modification History:
* Date Author Version Description
* -------------------------------------------------------------
* 2019/12/11 0011 Fu v1.0.0 创建
*/
public interface CacheService {
PageInfo list(String pattern, Integer page, Integer size); Boolean remove(String key); Object get(String key); void add(SysCach sysCach);
}
八、serviceImpl:
import java.util.ArrayList;
import java.util.List;
import java.util.Set; /**
* @ClassName: CacheServiceImpl
* @Description:
* @Version: v1.0.0
* @Author: Fu Hao
* @Date: 2019/12/11 0011 下午 7:54
* Modification History:
* Date Author Version Description
* -------------------------------------------------------------
* 2019/12/11 0011 Fu Hao v1.0.0 创建
*/
@Service("CacheService")
public class CacheServiceImpl implements CacheService { @Autowired
private StringRedisTemplate redisTemplate; /*** 返回所有符合条件的key
* @Description
* @author Fu Hao on 2019/12/11 0011 下午 8:14
* @param data description
* @return
**/
@Override
public PageInfo list(String pattern, Integer page, Integer size) {
page=page==null?0:page;
size=size==null?0:size;
pattern= StringUtils.isEmpty(pattern)?"*":pattern;
Set<String> keys=redisTemplate.keys("*"+pattern+"*");
List<SysCach> sysCachs=new ArrayList<>();
for (String key:keys){
SysCach sysCach=new SysCach();
//通过获取Redis里面的value
String value=redisTemplate.opsForValue().get(key);
Long outOfTime=redisTemplate.getExpire(key);
sysCach.setKey(key);
sysCach.setValue(value);
sysCach.setOutOfTime(outOfTime);
sysCachs.add(sysCach);
}
return new PageInfo<>(sysCachs);
} /***
* @Description 删除
* @author Fu Hao on 2019/12/11 0011 下午 8:46
* @param data description
* @return
**/
@Override
public Boolean remove(String key) {
return redisTemplate.delete(key);
} @Override
public Object get(String key) {
DataType dataType=redisTemplate.type(key);
Object val=null;
switch (dataType){
case NONE:
break;
case STRING:
val=redisTemplate.opsForValue().get(key);
break;
case SET:
val=redisTemplate.opsForSet().members(key);
break;
case HASH:
val=redisTemplate.opsForHash().entries(key);
break;
case LIST:
val=redisTemplate.opsForList().size(key);
break;
case ZSET:
val=redisTemplate.opsForZSet().size(key);
break;
default:
}
return val;
} @Override
public void add(SysCach sysCach) {
String key=sysCach.getKey();
String value=sysCach.getValue();
redisTemplate.opsForValue().set(key,value);
}
}