欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot整合Mysql和Redis的詳細(xì)過程

 更新時(shí)間:2022年02月23日 15:52:05   作者:路上的追夢人  
這篇文章主要介紹了SpringBoot整合Mysql和Redis的示例代碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、項(xiàng)目創(chuàng)建 

1.1 創(chuàng)建項(xiàng)目

在IDEA中,F(xiàn)ile--New--Project--Spring Initializer
名稱為springboot-mysql-redis

1.2 目錄結(jié)構(gòu)

1.3 pom.xml配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
    username: root
    password: 1234
    
  redis:
    host: localhost
    port: 6379
 
server:
  port: 8080
mybatis:
  mapper-locations: classpath:mapper/*xml
  type-aliases-package: com.xsbc.entity
  # 開啟駝峰命名
  configuration:
    map-underscore-to-camel-case: true

二、初始化數(shù)據(jù)庫

drop database if exists blog;
create database blog;
user blog;
drop table if exists user;
create table user(
	id int(11) not null,
	name varchar(255) DEFAULT "",
	age int(11) DEFAULT 0,
	PRIMARY KEY(id)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
 
insert into user values(1,'小王',20);
insert into user values(2,'老李',23);

三、初始化代碼

3.1 實(shí)體類entity

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String name;
    private int age;
}

3.2 Mapper接口類

@Mapper
public interface UserMapper {
    List<User> getAllUsers();
    int updateUser(Integer id);
}

 xml映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xsbc.mapper.UserMapper">
    <select id="getAllUsers" resultType="com.xsbc.entity.User">
        select * from user
    </select>
    
    <!--   User類的id參數(shù)是int類型,mysql默認(rèn)是Integer -->
    <update id="updateUserAgeById" parameterType="java.lang.Integer">
        update user set age=age+2 where id=#{id}
    </update>
</mapper>

3.3 Redis工具類

1)config包創(chuàng)建類

Redis常量類RedisConstant

public class RedisConstant {
    public static String ALL_USER_KEY="allUser";
}

Redis配置類RedisConfig

@Configuration
public class RedisConfig {
    @Resource
    private RedisTemplate redisTemplate;
 
    @Bean
    public RedisTemplate redisTemplateInit(){
        //序列化key的實(shí)例化對象
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //序列化value的實(shí)例化對象
        redisTemplate.setValueSerializer(
            new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }
}

2)util包下創(chuàng)建類

@Component
public class RedisUtil {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
 
    public void setRedisTemplate(RedisTemplate<String,Object> redisTemplate){
        this.redisTemplate=redisTemplate;
    }
    // 指定緩存失效時(shí)間
    public boolean expire(String key,long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    // 根據(jù)key獲取過期時(shí)間
    public long getExpire(String key){
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    // 判斷key是否存在
    public boolean hasKey(String key){
            return redisTemplate.hasKey(key);
        }catch(Exception e){
    // 刪除緩存
    @SuppressWarnings("unchecked")
    public void del(String... key){
        if (key!=null&&key.length> 0){
            if (key.length==1) {
                redisTemplate.delete(key[0]);
            }else{
              redisTemplate.delete(
                (Collection<String>)CollectionUtils.arrayToList(key));
    // 普通緩存獲取
    public Object get(String key){
        return key==null?null:redisTemplate.opsForValue().get(key);
    // 普通緩存放入
    public boolean set(String key,Object value){
            redisTemplate.opsForValue().set(key,value);
    // 普通緩存放入并設(shè)置時(shí)間
    public boolean set(String key,Object value,long time){
        try{
            if(time>0){
                redisTemplate.opsForValue()
                             .set(key,value,time,TimeUnit.SECONDS);
                set(key,value);
    // 遞增
    public long incr(String key,long delta){
        if(delta<0){
            throw new RuntimeException("遞增因子必須大于0");
        return redisTemplate.opsForValue().increment(key,delta);
    // 遞減
    public long decr(String key, long delta){
            throw new RuntimeException("遞減因子必須大于0");
        return redisTemplate.opsForValue().increment(key,-delta);
    // HashGet
    public Object hget(String key,String item){
        return redisTemplate.opsForHash().get(key,item);
    // 獲取hashKey對應(yīng)的所有鍵值
    public Map<Object, Object> hmget(String key){
        return redisTemplate.opsForHash().entries(key);
    // HashSet
    public boolean hmset(String key,Map<String, Object> map){
            redisTemplate.opsForHash().putAll(key,map);
    // HashSet 并設(shè)置時(shí)間
    public boolean hmset(String key,Map<String, Object> map,long time){
            redisTemplate.opsForHash().putAll(key, map);
            if (time>0){
                expire(key,time);
    // 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
    public boolean hset(String key,String item,Object value){
            redisTemplate.opsForHash().put(key,item,value);
    public boolean hset(String key,String item,Object value,long time){
    // 刪除hash表中的值
    public void hdel(String key,Object... item) {
        redisTemplate.opsForHash().delete(key,item);
    // 判斷hash表中是否有該項(xiàng)的值
    public boolean hHasKey(String key,String item) {
        return redisTemplate.opsForHash().hasKey(key,item);
    // hash遞增 如果不存在,就會創(chuàng)建一個(gè) 并把新增后的值返回
    public double hincr(String key,String item,double by) {
        return redisTemplate.opsForHash().increment(key,item,by);
    // hash遞減
    public double hdecr(String key,String item,double by) {
        return redisTemplate.opsForHash().increment(key,item,-by);
    // 根據(jù)key獲取Set中的所有值
    public Set<Object> sGet(String key) {
            return redisTemplate.opsForSet().members(key);
            return null;
    // 根據(jù)value從一個(gè)set中查詢,是否存在
    public boolean sHasKey(String key,Object value) {
            return redisTemplate.opsForSet().isMember(key,value);
    // 將數(shù)據(jù)放入set緩存
    public long sSet(String key,Object... values) {
            return redisTemplate.opsForSet().add(key,values);
            return 0;
    // 將set數(shù)據(jù)放入緩存
    public long sSetAndTime(String key,long time,Object... values){
            Long count=redisTemplate.opsForSet().add(key,values);
            if (time> 0)expire(key, time);
            return count;
    // 獲取set緩存的長度
    public long sGetSetSize(String key){
            return redisTemplate.opsForSet().size(key);
    // 移除值為value的
    public long setRemove(String key,Object... values){
            Long count=redisTemplate.opsForSet().remove(key,values);
    // 獲取list緩存的內(nèi)容
    public List<Object> lGet(String key,long start,long end){
            return redisTemplate.opsForList().range(key,start,end);
    // 獲取list緩存的長度
    public long lGetListSize(String key){
            return redisTemplate.opsForList().size(key);
    // 通過索引 獲取list中的值
    public Object lGetIndex(String key,long index){
            return redisTemplate.opsForList().index(key,index);
    // 將list放入緩存
    public boolean lSet(String key, Object value){
            redisTemplate.opsForList().rightPush(key,value);
    public boolean lSet(String key,Object value,long time){
            if (time > 0) expire(key, time);
    public boolean lSet(String key, List<Object> value){
            redisTemplate.opsForList().rightPushAll(key,value);
    public boolean lSet(String key,List<Object> value,long time){
            if(time>0) expire(key, time);
    // 根據(jù)索引修改list中的某條數(shù)據(jù)
    public boolean lUpdateIndex(String key,long index,Object value){
            redisTemplate.opsForList().set(key,index,value);
    // 移除N個(gè)值為value
    public long lRemove(String key,long count,Object value){
            Long remove=redisTemplate.opsForList().remove(key,count,value);
            return remove;
}

3.4 Service層

1)UserService接口類

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

2)接口實(shí)現(xiàn)類

@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
 
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public List<User> getAllUsers() {
        List<User> users=(List<User>)redisUtil
                            .get(RedisConstant.ALL_USER_KEY);
        if(CollectionUtils.isEmpty(users)){
            users=userMapper.getAllUsers();
            redisUtil.set(RedisConstant.ALL_USER_KEY,users);
        }
        return users;
    }
    @Transactional
    public void updateUserAge() {
        redisUtil.del(RedisConstant.ALL_USER_KEY);
        userMapper.updateUserAgeById(1);
        userMapper.updateUserAgeById(2);
}

3.5 Controller層

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    
    @RequestMapping("/getAll")
    @ResponseBody
    public List<User> getUsers(){
        return userService.getAllUsers();
    }
 
    @RequestMapping("/update")
    @ResponseBody
    public int updateUser(){
        userService.updateUserAge();
        return 1;
    }
}

四、單元測試

4.1 Respository和Service層單元測試

@SpringBootTest
class SpringbootMysqlRedisApplicationTests {
 
    @Autowired
    private UserMapper userMapper;
    private UserService userService;
    @Test
    void testUserMapper(){
        userMapper.updateUserAgeById(1);
        List<User> users=userMapper.getAllUsers();
        for(User user:users){
            System.out.println(user);
        }
    }
    void testUserService(){
        userService.updateUserAge();
        List<User> users=userService.getAllUsers();
}

4.2 Controller層接口測試

到此這篇關(guān)于SpringBoot整合Mysql、Redis的文章就介紹到這了,更多相關(guān)SpringBoot整合Mysql、Redis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java中的HashMap為什么會產(chǎn)生死循環(huán)

    Java中的HashMap為什么會產(chǎn)生死循環(huán)

    這篇文章主要介紹了Java中的HashMap為什么會產(chǎn)生死循環(huán),HashMap?死循環(huán)是一個(gè)比較常見、比較經(jīng)典的問題,下面文章我們就來徹底理解死循環(huán)的原因。需要的小伙伴可以參考一下
    2022-05-05
  • Java并發(fā)之Phaser的全面解析詳解

    Java并發(fā)之Phaser的全面解析詳解

    Phaser是Java中一個(gè)靈活的同步工具,其優(yōu)點(diǎn)在于支持多階段的任務(wù)拆分與同步,并且能夠動態(tài)地注冊與注銷參與者,下面我們就來深入了解一下Phaser的應(yīng)用吧
    2024-02-02
  • java開發(fā)web前端cookie session及token會話機(jī)制詳解

    java開發(fā)web前端cookie session及token會話機(jī)制詳解

    如果把人體比作一個(gè)web系統(tǒng)的話,cookie、session和token就好像人體的經(jīng)絡(luò)和血管一樣,而web系統(tǒng)中的數(shù)據(jù),就好像人體的血液一樣。血液依靠著血管在人體內(nèi)流動,就如數(shù)據(jù)根據(jù)cookie和session機(jī)制在web系統(tǒng)中流動一樣
    2021-10-10
  • SpringBoot的攔截器中依賴注入為null的解決方法

    SpringBoot的攔截器中依賴注入為null的解決方法

    這篇文章主要介紹了SpringBoot的攔截器中依賴注入為null的解決方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-06-06
  • Spring中Service注入多個(gè)實(shí)現(xiàn)類的方法詳解

    Spring中Service注入多個(gè)實(shí)現(xiàn)類的方法詳解

    這篇文章主要介紹了Spring中Service注入多個(gè)實(shí)現(xiàn)類的方法詳解,Spring是一個(gè)開源的Java框架,用于構(gòu)建企業(yè)級應(yīng)用程序,它提供了許多功能,如依賴注入、面向切面編程、數(shù)據(jù)訪問、Web開發(fā)等,需要的朋友可以參考下
    2023-07-07
  • Java如何發(fā)起http請求的實(shí)現(xiàn)(GET/POST)

    Java如何發(fā)起http請求的實(shí)現(xiàn)(GET/POST)

    這篇文章主要介紹了Java如何發(fā)起http請求的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • Java死鎖的產(chǎn)生原因及解決方法總結(jié)

    Java死鎖的產(chǎn)生原因及解決方法總結(jié)

    Java中的死鎖是指多個(gè)線程同時(shí)占用一些共享資源且彼此相互等待,從而導(dǎo)致所有的線程都被阻塞,不能繼續(xù)執(zhí)行程序的情況,本文小編給大家介紹了Java死鎖的產(chǎn)生原因及解決方法總結(jié),需要的朋友可以參考下
    2023-11-11
  • 利用Stream聚合函數(shù)如何對BigDecimal求和

    利用Stream聚合函數(shù)如何對BigDecimal求和

    這篇文章主要介紹了利用Stream聚合函數(shù)如何對BigDecimal求和問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • spring boot打包成war包的頁面如何存放

    spring boot打包成war包的頁面如何存放

    這篇文章主要介紹了spring boot打包成war包的頁面該放到哪里,很多朋友對這個(gè)問題都很疑惑,今天小編給大家分享一篇教程,需要的朋友可以參考下
    2019-11-11
  • 淺析NIO系列之TCP

    淺析NIO系列之TCP

    NIO即同步非阻塞式IO,它和傳統(tǒng)的BIO比較最大的區(qū)別在于在執(zhí)行accept、connect、read、write操作時(shí)是非阻塞的。很有利于實(shí)現(xiàn)用少量線程來處理多個(gè)客戶端請求,可以隨時(shí)讓線程切換所處理的客戶端,從而可以實(shí)現(xiàn)高并發(fā)服務(wù)器的開發(fā)
    2021-06-06

最新評論