三十六、Spring Boot使用Redis做集中式缓存

本文介绍如何在SpringBoot项目中使用Redis作为集中式缓存。包括添加依赖、配置属性、启用缓存、定义缓存操作的方法及测试缓存功能等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#                   Spring Boot使用Redis做集中式缓存

##1、添加redis缓存依赖

在pom.xml中添加以下依赖:

<!-- 连接redis -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

##2、在application.properties中声明redis地址

#redis缓存配置
spring.redis.host=192.168.9.88
spring.redis.port=6379
spring.redis.password=123456
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1

##3、在启动程序入口开启缓存

package com.yang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching   //开启缓存
public class DubboSpringbootOneApplication {

    public static void main(String[] args) {
        SpringApplication.run(DubboSpringbootOneApplication.class, args);
    }
}

##4、JPA实体类声明

package com.yang;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Enterprise implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Integer id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }

    @Override
    public String toString() {
        return "Enterprise [id=" + id + ", name=" + name + ", address=" + address + "]";
    }


}

##5、JPA接口声明

package com.yang;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;




/**
 * 继承JpaRepository  接口,实现JPA
 * @author yang
 */
@CacheConfig(cacheNames="enterprise")//<!-- 声明缓存使用的缓存名称 -->
public interface EnterpriseRepo extends JpaRepository<Enterprise, Integer>,JpaSpecificationExecutor<Enterprise>{
	
	//配置这个函数的返回值加入到缓存中,查询的时候先从缓存中获取,如果不存在再去数据库中查询。
	//除了@Cacheable,还有@CachePut和@CacheEvict。
	//@CachePut它每次都会调用函数,所以主要用于数据库新增和修改上。
	//@CacheEvict 配置函数上,通常用在删除方法上,用来从缓存中移除相应数据。
	@Cacheable(value="cash1",key="#p0")
	Enterprise findByid(Integer id);
	
	
  /*
   * 在spring boot中通过@EnableCaching注解自动化配置合适的缓存管理器。
   * Generic、JCache、EhCache。。。reids   
   * spring.chache.type强制指定缓存管理器。
   * 可以直接在resources下配置ehcache.xml,spring boot会自己侦测到。
   * 但是为了后期的演示,我们将其放到config文件夹中,并且改名为ehcache-config.xml,然后配置
   * 指定这个xml :spring.cache.ehchache.config=classpath:cofnig/ehcache-config.xml
   */
	@CachePut(value="cash1",key="#p0.id")
	Enterprise save(Enterprise enterprise);
	
}

##6、测试缓存

package com.yang;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DubboSpringbootOneApplicationTests {

	@Autowired
	private EnterpriseRepo enterprise;
	
	@Test
	public void contextLoads() {
		Enterprise enter1=enterprise.findByid(1);
		System.out.println("enter1:"+enter1);
		
		Enterprise enter3=new Enterprise();
		enter3.setId(1);
		enter3.setAddress("海南省海口市龙华区财富广场29楼");
		enter3.setName("凯亚");
		enterprise.save(enter3);
		
		Enterprise enter2=enterprise.findByid(1);
		System.out.println("enter2:"+enter2);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值