Springboot2.0 + jpa + redis緩存

本文基于Springboot2.0努释,使用mysql數(shù)據(jù)庫(kù),通過(guò)jpa實(shí)現(xiàn)orm咬摇,再用redis實(shí)現(xiàn)數(shù)據(jù)庫(kù)的緩存伐蒂。
目錄
1、項(xiàng)目結(jié)構(gòu)
2肛鹏、環(huán)境配置
3逸邦、代碼
4、測(cè)試
5在扰、參考文章


1缕减、項(xiàng)目結(jié)構(gòu)

項(xiàng)目結(jié)構(gòu)

2、環(huán)境配置

1)pom.xml

<dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        
        <!-- 引入Redis緩存 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        
    </dependencies>

2)application.yml
注意:

  • 創(chuàng)建mysql數(shù)據(jù)庫(kù)名稱(chēng)為 jpa_redis
  • redis 端口芒珠、
  • mysql 數(shù)據(jù)庫(kù)賬號(hào)密碼
server:
  port: 8081
 # context-path: /
spring:
  redis:
    host: localhost
    port: 6379
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jpa_redis
    username: root
    password: abc
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

3桥狡、代碼

1)SpringBootRedisApplication
注意添加 @EnableCaching

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

@SpringBootApplication
@EnableCaching
public class SpringBootRedisApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(SpringBootRedisApplication.class, args);
    }
}

2)RedisConfig

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.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.lang.reflect.Method;
import java.time.Duration;

/**
 * Redis 緩存配置類(lèi)
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{

    /**
     * 緩存對(duì)象集合中,緩存是以 key-value 形式保存的皱卓。
     * 當(dāng)不指定緩存的 key 時(shí)裹芝,SpringBoot 會(huì)使用 SimpleKeyGenerator 生成 key。
     */
//  @Bean
    public KeyGenerator wiselyKeyGenerator()
    {
        // key前綴娜汁,用于區(qū)分不同項(xiàng)目的緩存嫂易,建議每個(gè)項(xiàng)目單獨(dú)設(shè)置
        final String PRE_KEY = "test";  
        final char sp = ':';
        return new KeyGenerator()
        {
            @Override
            public Object generate(Object target, Method method, Object... params)
            {
                StringBuilder sb = new StringBuilder();
                sb.append(PRE_KEY);
                sb.append(sp);
                sb.append(target.getClass().getSimpleName());
                sb.append(sp);
                sb.append(method.getName());
                for (Object obj : params)
                {
                    sb.append(sp);
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory)
    {
        // 更改值的序列化方式,否則在Redis可視化軟件中會(huì)顯示亂碼掐禁。默認(rèn)為JdkSerializationRedisSerializer
        RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
                .fromSerializer(new GenericJackson2JsonRedisSerializer());
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration
                .defaultCacheConfig()
                .serializeValuesWith(pair)      // 設(shè)置序列化方式
                .entryTtl(Duration.ofHours(1)); // 設(shè)置過(guò)期時(shí)間

        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(factory))
                .cacheDefaults(defaultCacheConfig).build();
    }
}

3)實(shí)體類(lèi)User
注意實(shí)現(xiàn) Serializable 接口

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 用戶(hù)實(shí)體
 */
@Entity
@Table(name = "user")
public class User implements Serializable {
    private static final long serialVersionUID = 1l;
    
    @Id
    @GeneratedValue
    private Integer id;

    @Column(length = 20)
    private String userName;

    @Column(length = 20)
    private String password;

    public Integer getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

4)UserDao

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import com.cun.entity.User;

/**
 * 用戶(hù) dao 接口
 */
public interface UserDao extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User>
{

}

5)UserService

import java.util.List;

import com.cun.entity.User;

public interface UserService
{
    List<User> getAllUsers();

    User findById(Integer pId);
    
    void clearAllUserCache();
    
    void clear(Integer pId);
}

6)UserServiceImpl
cacheNamesvalue 作用一樣

import java.util.List;
import java.util.Optional;

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.cun.dao.UserDao;
import com.cun.entity.User;
import com.cun.service.UserService;

@Service
@CacheConfig(cacheNames = "userService")
public class UserServiceImpl implements UserService
{
    @Autowired
    private UserDao userDao;

    /**
     * cacheNames 與 value 定義一樣怜械,設(shè)置了 value 的值,則類(lèi)的 cacheNames 配置無(wú)效傅事。<br>
     * 使用 keyGenerator 缕允,注意是否在config文件中定義好。
     * @see com.cun.service.UserService#getAllUsers()
     */
    @Override
    @Cacheable(value = "getAllUsers")
//  @Cacheable(value = "getAllUsers", keyGenerator = "wiselyKeyGenerator")
    public List<User> getAllUsers()
    {
        return userDao.findAll();
    }
    
    /**
     * 執(zhí)行該函數(shù)時(shí)蹭越,將清除以 userService 的緩存障本,【cacheNames = "userService"】<br>
     * 也可指定清除的key 【@CacheEvict(value="abc")】
     */
    @CacheEvict(value = "getAllUsers")
    public void clearAllUserCache()
    {
        
    }
    
    /**
     * key ="#p0" 表示以第1個(gè)參數(shù)作為 key
     */
    @Override
    @Cacheable(value="user", key ="#p0")
    public User findById(Integer pId)
    {
        Optional<User> _User = userDao.findById(pId);
        
        return Optional.ofNullable(_User).get().orElse(null);
    }
    
    @CacheEvict(value="user", key ="#p0")
    public void clear(Integer pId)
    {
        
    }
}

7)UserController

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cun.entity.User;
import com.cun.service.UserService;


/**
 * 參考 https://blog.csdn.net/larger5/article/details/79696562
 */
@RestController
public class UserController
{
    @Autowired
    private UserService userService;

    // http://localhost:8081/all
    @GetMapping("/all")
    public List<User> getAllUsers()
    {
        System.out.println("只有第一次才會(huì)打印sql語(yǔ)句");
        return userService.getAllUsers();
    }

    // http://localhost:8081/findById?id=1
    @GetMapping("/findById")
    public User findById(@RequestParam(name = "id")Integer pId)
    {
        return userService.findById(pId);
    }
    
    // http://localhost:8081/clear
    @GetMapping("/clear")
    public void clear()
    {
        userService.clearAllUserCache();
    }
    
    // http://localhost:8081/clearOne?id=1
    @GetMapping("/clearOne")
    public void clear(@RequestParam(name = "id")Integer pId)
    {
        userService.clear(pId);
    }
}

4、測(cè)試

啟動(dòng)服務(wù)后般又,可以看到 jpa 框架自動(dòng)生成 user 表


user表

1)添加測(cè)試數(shù)據(jù)

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.*;

import com.cun.SpringBootRedisApplication;
import com.cun.dao.UserDao;
import com.cun.entity.User;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=SpringBootRedisApplication.class)
public class AddTester {
    @Autowired
    private UserDao userDao;
    @Test
    public void test()
    {
        User _User = new User();
        _User.setPassword("123");
        _User.setUserName("老王");
        userDao.save(_User);
        
        User _User2 = new User();
        _User2.setPassword("456");
        _User2.setUserName("小李");
        userDao.save(_User2);
    }
}

2)緩存測(cè)試
訪(fǎng)問(wèn) http://localhost:8081/all 彼绷,可看到緩存數(shù)據(jù)

image.png

訪(fǎng)問(wèn) http://localhost:8081/findById?id=1,可看到緩存數(shù)據(jù)

image.png

則調(diào)用 http://localhost:8081/clear 后茴迁,getAllUsers 的緩存將被清除寄悯;
則調(diào)用 http://localhost:8081/clearOne?id=1 后,user::1 的緩存將被清除堕义。

5猜旬、參考文章

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市倦卖,隨后出現(xiàn)的幾起案子洒擦,更是在濱河造成了極大的恐慌,老刑警劉巖怕膛,帶你破解...
    沈念sama閱讀 219,188評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件熟嫩,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡褐捻,警方通過(guò)查閱死者的電腦和手機(jī)掸茅,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)柠逞,“玉大人昧狮,你說(shuō)我怎么就攤上這事“遄常” “怎么了逗鸣?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,562評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀(guān)的道長(zhǎng)绰精。 經(jīng)常有香客問(wèn)我撒璧,道長(zhǎng),這世上最難降的妖魔是什么笨使? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,893評(píng)論 1 295
  • 正文 為了忘掉前任沪悲,我火速辦了婚禮,結(jié)果婚禮上阱表,老公的妹妹穿的比我還像新娘殿如。我一直安慰自己,他們只是感情好最爬,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布涉馁。 她就那樣靜靜地躺著,像睡著了一般爱致。 火紅的嫁衣襯著肌膚如雪烤送。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,708評(píng)論 1 305
  • 那天糠悯,我揣著相機(jī)與錄音帮坚,去河邊找鬼妻往。 笑死,一個(gè)胖子當(dāng)著我的面吹牛试和,可吹牛的內(nèi)容都是我干的讯泣。 我是一名探鬼主播,決...
    沈念sama閱讀 40,430評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼阅悍,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼好渠!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起节视,我...
    開(kāi)封第一講書(shū)人閱讀 39,342評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤拳锚,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后寻行,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體霍掺,經(jīng)...
    沈念sama閱讀 45,801評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評(píng)論 3 337
  • 正文 我和宋清朗相戀三年拌蜘,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了抗楔。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,115評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡拦坠,死狀恐怖连躏,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情贞滨,我是刑警寧澤入热,帶...
    沈念sama閱讀 35,804評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站晓铆,受9級(jí)特大地震影響勺良,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜骄噪,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評(píng)論 3 331
  • 文/蒙蒙 一尚困、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧链蕊,春花似錦事甜、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,008評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至陪蜻,卻和暖如春邦马,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,135評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工滋将, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留邻悬,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,365評(píng)論 3 373
  • 正文 我出身青樓随闽,卻偏偏與公主長(zhǎng)得像父丰,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子橱脸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容