项目结构概览:

1. 导包

    <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- 跳过test打包 -->
<skipTests>true</skipTests>
</properties> <dependencies>
<!--web场景启动器,包含 Tomcat 和 spring-mvc restful aop jackjson支持。 -->
<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>
<!-- ehcache缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- commons-lang3工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!--指定主函数路径
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.codingapi.txlcn.tm.TMApplication</mainClass>
</manifest>
</archive>
</configuration>-->
</plugin>
</plugins>
</build>
  <!--
没有Main函数打包
  <build>
   <plugins>
   <plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-assembly-plugin</artifactId>
   </plugin>
  </plugins>
  </build>
  -->

2.1 application.properties配置文件

# 运行端口
server.port=8084
# 项目访问路径前缀
server.context-path=/cache # 服务名称
spring.application.name=springbootTest
# ehcache配置文件
spring.cache.ehcache.config=classpath:ehcacheproduct.xml

2.2 redis.properties配置参数

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
#spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=1024
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=10000
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=200
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=10000
#flase:超时就报错,   true:阻塞到超时
spring.redis.block-when-exhausted=true

2.3 ehcacheproduct.xml配置问价

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"> <!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir" /> <!--
name: 缓存名称
maxElementsInMemory: 缓存最大个数
maxEntriesLocalHeap: 在内存创建对象的最大数量,0=无限制。
maxEntriesLocalDisk: 硬盘上存储的对象的最大数量。默认0,即无限制
eternal: 对象是否永久有效,一但设置了, timeout将不起作用
timeToIdleSeconds: 当缓存闲置n秒后销毁 ,默认是0,也就是对象存活时间无穷大。当eternal=false时有效!
timeToLiveSeconds: 当缓存存活n秒后销毁 ,默认是0,也就是对象存活时间无穷大。当eternal=false时有效!
overflowToDisk: 达到缓存maxElementsInMemory个数后,将数据存入磁盘,默认大小为30mb
diskPersistent: 是否缓存虚拟机重启期数据
diskExpiryThreadIntervalSeconds: 磁盘失效线程运行时间间隔,默认是120秒。达到缓存最大个数,会按照磁盘清理策略去清理磁盘。
memoryStoreEvictionPolicy: 磁盘清理策略, 默认策略LRU(最近最少使用)你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush: 内存数量最大时是否清除
-->
<!-- 默认缓存 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap" />
</defaultCache> <!-- 自定义缓存 -->
<cache name="userchache"
eternal="false"
timeToIdleSeconds="2400"
timeToLiveSeconds="2400"
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU">
</cache>
</ehcache>

3. RedisConfig配置文件

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; @Configuration
@PropertySource("classpath:redis.properties")
public class RedisConfig {
private final Logger log = LoggerFactory.getLogger(this.getClass()); @Value("${spring.redis.host}")
private String host; @Value("${spring.redis.port}")
private int port; @Value("${spring.redis.timeout}")
private int timeout; @Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle; @Value("${spring.redis.jedis.pool.max-wait}")
private long maxWaitMillis; //@Value("${spring.redis.password}")
//private String password;
private String password; @Value("${spring.redis.block-when-exhausted}")
private boolean blockWhenExhausted; @Bean
public JedisPool redisPoolFactory() throws Exception{
log.info("-------------JedisPool注入成功!!----------------");
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
// 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
// 是否启用pool的jmx管理功能, 默认true
jedisPoolConfig.setJmxEnabled(true);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password); return jedisPool;
}
}

4. Redis工具类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@Component
public class RedisUtil{
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private JedisPool jedisPool; public String get(String key) {
Jedis jedis = null;
String value = null;
try {
jedis = jedisPool.getResource();
value = jedis.get(key);
log.info(value);
} catch (Exception e) { log.error(e.getMessage());
} finally {
returnResource(jedis);
}
return value;
} public String set(String key, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.set(key, value);
} catch (Exception e) { log.error(e.getMessage());
return "0";
} finally {
returnResource(jedis);
}
} /**
* 关闭连接
*/
public static void returnResource(Jedis jedis) {
try {
jedis.close();
} catch (Exception e) {
}
}
}

5. 测试业务逻辑

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.wulei.model.User;
import com.wulei.utils.RedisUtil;
@Service
// 指定ehcache缓存规则
@CacheConfig(cacheNames = "userchache")
public class UserService {
@Autowired
RedisUtil redisUtil; public List<User> testRedis() {
redisUtil.set("name", "吴磊");
System.out.println(redisUtil.get("name"));
return this.getDataSource();
} @Cacheable(key="'testEhcaheCacheable'")
public List<User> testEhcaheCacheable(){
// 只会查询一次
System.out.println("Cacheable查询缓存数据");
return this.getDataSource();
} //键为"userId:"字符串加上userId值,如 'userId:1'
@CacheEvict(key="'userId:' + #userId")
public List<User> testEhcaheCacheEvict(int userId){
// 每次请求都会删除指定key
System.out.println("清除userchache中指定key的缓存");
List<User> list = this.getDataSource();
list.remove(userId-1);
return list;
} @CacheEvict(allEntries=true)
public List<User> testEhcaheCacheEvictAll(){
// 每次请求都会删除所有key
System.out.println("清除userchache中所有key的缓存");
return new ArrayList<User>();
} public List<User> getDataSource(){
List<User> list = new ArrayList<User>();
list.add(new User(1, "jay", 21));
list.add(new User(2, "join", 22));
list.add(new User(3, "eason", 23));
list.add(new User(4, "jj", 24));
return list;
}
}

6. controller入口

@RestController
public class UserController { @Autowired
private UserService userService; @RequestMapping("/testRedis")
public List<User> testRedis() {
return userService.testRedis();
}
@RequestMapping("/testEhcahe")
public List<User> testEhcahe(int type){
if(type==1) {
return userService.testEhcaheCacheable();
}else if(type==2) {
return userService.testEhcaheCacheEvict(type);
}else if(type==3) {
return userService.testEhcaheCacheEvictAll();
}
return null;
}
}

7. 主函数

@SpringBootApplication
@EnableCaching // 启用ehcache缓存注解
public class Application { private static Logger log = Logger.getLogger(Application.class); public static void main(String[] args) {
SpringApplication.run(Application.class, args);
log.info("SpringBoot Start Success");
}
}

<parent>         <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>1.5.8.RELEASE</version>        <relativePath/>     </parent>    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>        <java.version>1.8</java.version><!-- 跳过test打包 -->        <skipTests>true</skipTests>    </properties>        <dependencies>        <!--web场景启动器,包含 Tomcat 和 spring-mvc restful  aop jackjson支持。 -->        <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>        <!-- ehcache缓存 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-cache</artifactId>        </dependency>        <!-- redis -->        <dependency>            <groupId>redis.clients</groupId>            <artifactId>jedis</artifactId>            <type>jar</type>            <scope>compile</scope>        </dependency>        <!-- commons-lang3工具类 -->        <dependency>            <groupId>org.apache.commons</groupId>            <artifactId>commons-lang3</artifactId>            <version>3.7</version>        </dependency>    </dependencies>      <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>                <!--指定主函数路径                <configuration>                    <archive>                        <manifest>                            <addClasspath>true</addClasspath>                            <classpathPrefix>lib/</classpathPrefix>                            <mainClass>com.codingapi.txlcn.tm.TMApplication</mainClass>                        </manifest>                    </archive>                </configuration>-->            </plugin>        </plugins>    </build>    <!--    没有Main函数打包  <build>      <plugins>          <plugin>             <groupId>org.apache.maven.plugins</groupId>              <artifactId>maven-assembly-plugin</artifactId>          </plugin>      </plugins>  </build>  -->

Springboot+Jedis+Ehcache整合的更多相关文章

  1. Springboot使用ehcache缓存

    本文部分步骤继承于springboot使用cache缓存,如果有不清楚的,请移驾springboot使用cache缓存 ehcache是一种广泛使用的开源Java分布式缓存.主要面向通用缓存,Java ...

  2. SpringBoot 优雅的整合 Shiro

    Apache Shiro是一个功能强大且易于使用的Java安全框架,可执行身份验证,授权,加密和会话管理.借助Shiro易于理解的API,您可以快速轻松地保护任何应用程序 - 从最小的移动应用程序到最 ...

  3. SpringBoot+Shiro+mybatis整合实战

    SpringBoot+Shiro+mybatis整合 1. 使用Springboot版本2.0.4 与shiro的版本 引入springboot和shiro依赖 <?xml version=&q ...

  4. Ehcache 整合Spring 使用页面、对象缓存

    Ehcache 整合Spring 使用页面.对象缓存 Ehcache在很多项目中都出现过,用法也比较简单.一 般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布 ...

  5. ehcache整合spring本地接口方式

    一.简介 ehcache整合spring,可以通过使用echache的本地接口,从而达到定制的目的.在方法中根据业务逻辑进行判断,从缓存中获取数据或将数据保存到缓存.这样让程序变得更加灵活. 本例子使 ...

  6. 八 mybatis查询缓存(一级缓存,二级缓存)和ehcache整合

    1       查询缓存 1.1     什么是查询缓存 mybatis提供查询缓存,用于减轻数据压力,提高数据库性能. mybaits提供一级缓存,和二级缓存.

  7. mybatis 与 ehcache 整合[转]

    1.简介 MyBatis 是支持普通SQL 查询,存储过程和高级映射的优秀持久层框架.MyBatis 消除了几乎所有的JDBC 代码和参数的手工设置以及结果集的检索. Ehcache 是现在最流行的纯 ...

  8. SpringBoot与Mybatis整合方式01(源码分析)

    前言:入职新公司,SpringBoot和Mybatis都被封装了一次,光用而不知道原理实在受不了,于是开始恶补源码,由于刚开始比较浅,存属娱乐,大神勿喷. 就如网上的流传的SpringBoot与Myb ...

  9. Springboot security cas整合方案-实践篇

    承接前文Springboot security cas整合方案-原理篇,请在理解原理的情况下再查看实践篇 maven环境 <dependency> <groupId>org.s ...

随机推荐

  1. Linux培训教程 linux系统下分割大文件的方法

    在linux中分割大文件,比如一个5gb日志文件,需要把它分成多个小文件,分割后以利于普通的文本编辑器读取. 有时,需要传输20gb的大文件,Linux培训 教程件到另一台服务器,也需要把它分割成多个 ...

  2. XML 文档包含 XML 元素。

    XML 文档包含 XML 元素. 什么是 XML 元素? XML 元素指的是从(且包括)开始标签直到(且包括)结束标签的部分. 元素可包含其他元素.文本或者两者的混合物.元素也可以拥有属性. < ...

  3. UVa 725 Division (枚举)

    题意 : 输入正整数n,按从小到大的顺序输出所有形如abcde/fghij = n的表达式,其中a-j恰好为数字0-9的一个排列(可以有前导0),2≤n≤79. 分析 : 最暴力的方法莫过于采用数组存 ...

  4. 【spoj2774】最长公共子串

    题目描述: 给你两个字符串,求它们最长公共子串的长度,如果不存在公共子串则输出0. 样例输入: yeshowmuchiloveyoumydearmotherreallyicannotbelieveit ...

  5. 举例子说明ubuntu中remove,autoremove,purge区别

    转自:慎用 apt-get autoremove !   apt-get 提供了一个用于下载和安装软件包的简易命令行界面.卸载软件包主要有这3个命令 remove – 卸载软件包autoremove ...

  6. POJ 3260 The Fewest Coins(完全背包+多重背包=混合背包)

    题目代号:POJ 3260 题目链接:http://poj.org/problem?id=3260 The Fewest Coins Time Limit: 2000MS Memory Limit: ...

  7. JMS学习四(ActiveMQ消息过滤)

    一.消息的选择器 不管是在消息发送端设置消息过期时间还是在接收端设置等待时间,都是对不满足的消息有过滤的作用,那消息选择器就是为过滤消息而生的下面来看看消息选择器: ActiveMQ提供了一种机制,使 ...

  8. BZOJ 1859 Luogu P2589 [ZJOI2006]碗的叠放 (计算几何)

    woc, 13年前的ZJOI就这么毒瘤的嘛... 题目链接: (bzoj)https://www.lydsy.com/JudgeOnline/problem.php?id=1859 (luogu)ht ...

  9. sqli-labs(28)---原创原创自此一家

    0X01构造闭合 ’报错 )报错 其他不报错 那我们猜想是不是')的闭合 ?id=')=('1 返回正确 那么好像猜对了 0X02爆表名 过滤了相连接的union和select ?id= 这里过滤了相 ...

  10. 第四周总结 & 实验报告(二)

    第四周课程总结 一.String类 1.实例化 (1)直接赋值 public class Xxxx{ public static void main(String args[]){ String a ...