1. <ul id="0c1fb"></ul>

      <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
      <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区

      RELATEED CONSULTING
      相關(guān)咨詢
      選擇下列產(chǎn)品馬上在線溝通
      服務(wù)時間:8:30-17:00
      你可能遇到了下面的問題
      關(guān)閉右側(cè)工具欄

      新聞中心

      這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
      Redis框架如何搭建SpringBoot2.X

      這篇文章主要介紹redis框架如何搭建SpringBoot2.X,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

      專注于為中小企業(yè)提供成都網(wǎng)站設(shè)計、做網(wǎng)站、成都外貿(mào)網(wǎng)站建設(shè)公司服務(wù),電腦端+手機端+微信端的三站合一,更高效的管理,為中小企業(yè)大安免費做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了成百上千企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實現(xiàn)規(guī)模擴充和轉(zhuǎn)變。

      一、使用Spring Initializr創(chuàng)建項目web項目

      1、File→New→Project

      Redis框架如何搭建SpringBoot2.X

      2、點擊Next如圖所示,命名好Group和Artifact

      Redis框架如何搭建SpringBoot2.X

      3、Next后如圖所示,勾選中需要的依賴,Spring Initializr會自動導入所需的starter

      Redis框架如何搭建SpringBoot2.X

      4、創(chuàng)建項目成功后,pom.xml文件中的依賴如下

      
      
      	4.0.0
      	
      		org.springframework.boot
      		spring-boot-starter-parent
      		2.2.2.RELEASE
      		 
      	
      	com.heny
      	spring-boot-redis
      	0.0.1-SNAPSHOT
      	spring-boot-redis
      	Demo project for Spring Boot
      
      	
      		1.8
      	
      
      	
      		
      			org.springframework.boot
      			spring-boot-starter-web
      		
      		
      			org.mybatis.spring.boot
      			mybatis-spring-boot-starter
      			2.1.1
      		
      
      		
      			MySQL
      			mysql-connector-java
      			runtime
      		
      		
      			org.springframework.boot
      			spring-boot-starter-test
      			test
      			
      				
      					org.junit.vintage
      					junit-vintage-engine
      				
      			
      		
      	
      
      	
      		
      			
      				org.springframework.boot
      				spring-boot-maven-plugin
      			
      		
      	
      
      

      5、在pom.xml文件中添加redis的starter

      
      		org.springframework.boot
      		spring-boot-starter-data-redis
      	

      6、創(chuàng)建JavaBean用于封裝數(shù)據(jù)庫數(shù)據(jù),需要實現(xiàn)Serializable

      package com.henya.springboot.bean;
      
      import java.io.Serializable;
      
      public class Employee implements Serializable{
      	
      	private Integer id;
      	private String lastName;
      	private String email;
      	private Integer gender; //性別 1男 0女
      	private Integer dId;
      	
      	
      	public Employee() {
      		super();
      	}
      
      	
      	public Employee(Integer id, String lastName, String email, Integer gender, Integer dId) {
      		super();
      		this.id = id;
      		this.lastName = lastName;
      		this.email = email;
      		this.gender = gender;
      		this.dId = dId;
      	}
      	
      	public Integer getId() {
      		return id;
      	}
      	public void setId(Integer id) {
      		this.id = id;
      	}
      	public String getLastName() {
      		return lastName;
      	}
      	public void setLastName(String lastName) {
      		this.lastName = lastName;
      	}
      	public String getEmail() {
      		return email;
      	}
      	public void setEmail(String email) {
      		this.email = email;
      	}
      	public Integer getGender() {
      		return gender;
      	}
      	public void setGender(Integer gender) {
      		this.gender = gender;
      	}
      	public Integer getdId() {
      		return dId;
      	}
      	public void setdId(Integer dId) {
      		this.dId = dId;
      	}
      	@Override
      	public String toString() {
      		return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", dId="
      				+ dId + "]";
      	}
      }

      注意:
      在寫JavaBean對象時需要實現(xiàn)Serializable接口否則會報以下錯誤:

      Cannot deserialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException

      7、整合Mybatis操作數(shù)據(jù)庫,在application.properties配置文件中配置數(shù)據(jù)源信息

      #serverTimezone用于指定時區(qū),不然會報錯
      spring.datasource.url=jdbc:mysql://localhost:3306/cache?serverTimezone=UTC
      spring.datasource.username=root
      spring.datasource.password=123456
      
      # 開啟駝峰命名法規(guī)則
      mybatis.configuration.map-underscore-to-camel-case=true
      #日志級別
      logging.level.com.henya.springboot.mapper=debug

      8、使用注解版Mybatis創(chuàng)建Mapper

      package com.henya.springboot.mapper;
      
      
      import com.henya.springboot.bean.Employee;
      import org.apache.ibatis.annotations.*;
      
      @Mapper
      public interface EmployeeMapper {
      
       @Select("SELECT * FROM employee WHERE id=#{id}")
       public Employee getEmpById(Integer id);
      
       @Update("UPDATE employee SET lastName=#{lastName},email=#{email},gender=#{gender},d_id=#{dId} WHERE id=#{id}")
       public void updateEmp(Employee employee);
      
       @Delete("DELETE FROM emlpoyee WHERE id=#{id}")
       public void delEmpById(Integer id);
      
       @Insert("INSERT INTO employee(lastName, email, gender, d_id) VALUES (#{lastName}, #{email}, #{gender}, #{dId})")
       public Employee insertEmp(Employee employee);
      
       @Select("SELECT * FROM employee WHERE lastName=#{lastName}")
       public Employee getEmpByLastName(String lastName);
      }

      注意:
      需要使用使用@MapperScan注解掃描Mapper所在的接口,只需要加在主程序類上即可。除此之外,還要使用@EnableCaching用于開啟緩存。

      @MapperScan("com.henya.springboot.mapper")
      @SpringBootApplication
      @EnableCaching //開啟緩存
      public class SpringBootRedisApplication {
      
      	public static void main(String[] args) {
      		SpringApplication.run(SpringBootRedisApplication.class, args);
      	}
      }

      9、編寫Service類,用于訪問數(shù)據(jù)庫或redis緩存

      package com.henya.springboot.service;
      import com.henya.springboot.bean.Employee;
      import com.henya.springboot.mapper.EmployeeMapper;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.cache.annotation.*;
      import org.springframework.stereotype.Service;
      
      @CacheConfig(cacheNames = "emp") //抽取緩存的公共配置
      @Service
      public class EmployeeService {
       @Autowired
       EmployeeMapper employeeMapper;
      
       /**
       * @param id
       * @return
       */
       @Cacheable(cacheNames = {"emp"},keyGenerator = "myKeyGenerator")
       public Employee getEmpById(Integer id) {
       System.err.println("開始查詢"+ id +"號員工");
       Employee employee = employeeMapper.getEmpById(id);
       return employee;
       }
      
       /**
       * @CachePut:既調(diào)用方法(這個方法必須要執(zhí)行),又更新緩存數(shù)據(jù)
       * @param employee
       * @return
       */
       @CachePut(value = "emp",key = "#result.id")
       public Employee updateEmp(Employee employee){
       System.err.println("開始更新" + employee.getId() + "號員工");
       employeeMapper.updateEmp(employee);
       return employee;
       }
      
       /**
       * @CacheEvict:緩存清除
       * @param id
       */
       @CacheEvict(value = "emp",beforeInvocation = true)
       public void deleteEmp(Integer id){
       System.err.println("刪除" + id + "員工");
       int i = 10/0;
       }

      10、編寫Controller類

      package com.henya.springboot.controller;
      
      
      import com.henya.springboot.bean.Employee;
      import com.henya.springboot.service.EmployeeService;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.PathVariable;
      import org.springframework.web.bind.annotation.RestController;
      
      /**
       * @Description:
       * @Author:HenYa
       * @CreatTime:2019/12/1 12:44
       */
      @RestController
      public class EmployeeController {
       @Autowired
       EmployeeService employeeService;
      
       @GetMapping("/emp/{id}")
       public Employee getEmpById(@PathVariable("id") Integer id){
       Employee employee = employeeService.getEmpById(id);
       return employee;
       }
      
       @GetMapping("/emp")
       public Employee updateEmp(Employee employee){
       Employee emp = employeeService.updateEmp(employee);
       return emp;
       }
      }

      二、測試SpringBoot整合Redis是否成功

      1、在瀏覽器訪問,也可以使用測試類,筆者使用了瀏覽器訪問http://localhost:8080/emp/1進行測試,初次訪問時,控制臺會提示開始查詢1號員工,如圖所示。

      Redis框架如何搭建SpringBoot2.X

      2、再次訪問時,控制臺并沒有sql日志,如圖所示。

      Redis框架如何搭建SpringBoot2.X

      3、此時使用RedisDesktopManager工具查看redis時有數(shù)據(jù),并且cacheName為emp,如圖所示

      Redis框架如何搭建SpringBoot2.X

      只是emp對象被序列化了。查看源碼可知Redis默認使用Jdk進行序列化。

      static RedisSerializer java(@Nullable ClassLoader classLoader) {
       return new JdkSerializationRedisSerializer(classLoader);
       }

      查看RedisSerializer接口的實現(xiàn)有以下幾種:

      Redis框架如何搭建SpringBoot2.X

      我們常用的就是以json的格式進行序列化。但是需要自定義RedisCacheManager。

      三、自定義RedisCacheManager

      package com.henya.springboot.config;
      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 org.springframework.data.redis.serializer.RedisSerializer;
      
      /**
       * @Description:
       * @Author:HenYa
       * @CreatTime:2019/12/6 20:50
       */
      @Configuration
      public class MyRedisConfig {
       @Bean
       public RedisCacheManager empCacheManager(RedisConnectionFactory redisConnectionFactory){
       //RedisCacheManager redisCacheManager = new RedisCacheManager(redisConnectionFactory);
       RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
      
       RedisSerializer redisSerializer = new GenericJackson2JsonRedisSerializer();
      
       RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer);
       RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
       // 默認會將CacheName作為key的前綴
       return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
       }
       }

      以上是“Redis框架如何搭建SpringBoot2.X”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!


      網(wǎng)頁名稱:Redis框架如何搭建SpringBoot2.X
      URL分享:http://ef60e0e.cn/article/jojiii.html 99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区
          1. <ul id="0c1fb"></ul>

            <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
            <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

            内黄县| 广水市| 准格尔旗| 张掖市| 石屏县| 武城县| 湖北省| 博湖县| 六安市| 石台县| 新安县| 大石桥市| 诸暨市| 金堂县| 郸城县| 太仆寺旗| 孟津县| 科技| 临邑县| 望江县| 渭源县| 临澧县| 亳州市| 高唐县| 宁化县| 阳高县| 琼结县| 织金县| 天镇县| 永嘉县| 洪湖市| 芮城县| 油尖旺区| 西和县| 临高县| 辛集市| 平南县| 苍溪县| 敖汉旗| 石河子市| 苏州市|