SpringBoot-EhCache使用

创建SpringBoot工程

创建如下类:
@Entity
public class User {
    @Id
    @GeneratedValue
    private long  id;

    @Column(nullable = false)
    private  String name;

    @Column(nullable = false)
    private Integer age;
    ......省略getter和setter方法
}
jpa查询接口
public interface UserRepository extends JpaRepository<User,Long> {

    User findByNameAndAge(String name, Integer age);

    @Query("from User u where u.name=:name")
    User findUser(@Param("name") String name);
    @Cacheable
    User findByName(String name);
}
application.yml配置
spring:
    datasource:
          url:  jdbc:mysql://localhost:3306/test
          username: root
          password: ******
          driver-class-name: com.mysql.jdbc.Driver
    jpa:
      hibernate:
        ddl-auto: update
      show-sql: true
Test测试类
    @Autowired
    private UserRepository userRepository;
    @Before
    public void before() {
        userRepository.save(new User("BBB", 20));
    }
    @Test
    public void test() throws Exception {
        User user1 = userRepository.findByName("BBB");
        System.out.println("第一次查询:" + user1.getAge());
        User user2 = userRepository.findByName("BBB");
        System.out.println("第二次查询:" + user2.getAge());
    }
运行结果图

这里写图片描述

引入EhCache缓存依赖包
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
    在入口程序加入@EnableCaching注解
@SpringBootApplication
@EnableCaching
public class SpringbootCacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootCacheApplication.class, args);
    }
}
数据接口中加入缓存注解
@CacheConfig(cacheNames = "user")
public interface UserRepository extends JpaRepository<User,Long> {
    @Cacheable
    User findByName(String name);
}
测试结果

这里写图片描述

注解含义:

@CacheConfig(cacheNames =”user”)将共用的查询结果放在user对象中
@Cacheable 配置了findByName函数的返回值将被加入缓存。同时在查询时,会先从缓存中获取,若不存在才再发起对数据库的访问
具体参考:(http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html)
(http://blog.didispace.com/springbootcache1)

在Spring Boot中整合Ehcache缓存,需要进行以下几个步骤: 1. 添加Ehcache依赖 在pom.xml文件中添加Ehcache依赖: ``` <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> </dependency> ``` 2. 配置Ehcache缓存 在application.yml(或application.properties)文件中配置Ehcache缓存: ``` spring: cache: type: ehcache ehcache: config: classpath:ehcache.xml ``` 其中,`spring.cache.type`属性指定使用的缓存类型为Ehcache,`ehcache.config`属性指定Ehcache配置文件的路径(在classpath下)。 3. 编写Ehcache配置文件 在classpath下创建`ehcache.xml`文件,配置Ehcache缓存的相关信息: ``` <ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" transactionalMode="off"> </defaultCache> <cache name="userCache" maxEntriesLocalHeap="1000" maxEntriesLocalDisk="10000" eternal="false" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" transactionalMode="off"> </cache> </ehcache> ``` 其中,`defaultCache`为默认缓存配置,`cache`为自定义缓存配置。 4. 在代码中使用缓存 在需要使用缓存的方法上添加`@Cacheable`注解,指定缓存名称和缓存key: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override @Cacheable(value = "userCache", key = "#id") public User getUserById(Integer id) { return userDao.getUserById(id); } // ... } ``` 其中,`value`属性指定缓存名称,`key`属性为缓存key表达式,可以使用Spring表达式语言(SpEL)进行动态表达。 以上就是在Spring Boot中整合Ehcache缓存的步骤,通过使用Ehcache缓存可以有效地提高应用程序的性能和响应速度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值