1. 程式人生 > 其它 >SpringBoot(四)SpringBoot整合Redis

SpringBoot(四)SpringBoot整合Redis

技術標籤:redisjedisjavaspring boot

SpringBoot(四)SpringBoot整合Redis

<!-- redis依賴包 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
#配置連線Redis
#主機地址
spring.redis.host=IP
#埠號
spring.redis.port=6379
#連線的超時時間
spring.redis.timeout=3000
#redis連線池
#連線池最大連線數
spring.redis.jedis.pool.max-active=8
#最大阻塞等待時間
spring.redis.jedis.pool.max-wait=3000
#最大空閒連線數
spring.redis.jedis.pool.max-idle=8
#最小空閒連線數
spring.redis.jedis.pool.min-idle=2
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 讀取快取
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 寫入快取
     */
    public
boolean set( String key, Object value) { boolean result = false; try { redisTemplate.opsForValue().set(key, value,1, TimeUnit.DAYS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 更新快取 */
public boolean getAndSet(final String key, String value) { boolean result = false; try { redisTemplate.opsForValue().getAndSet(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 刪除快取 */ public boolean delete(final String key) { boolean result = false; try { redisTemplate.delete(key); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } }
public class Article implements Serializable {
    private Integer id;
    private String title;
    private String content;
}
@RunWith(SpringRunner.class)
@SpringBootTest
class BootmybatisApplicationTests {
    
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private RedisUtils redisUtils;

    //寫入,key :1 ,value :MySQL資料庫中id為1的article記錄
    @Test
    void insertRedis(){
        redisUtils.set("1",articleMapper.selectArticle(1));
        System.out.println("success");
    }
    
    @Test
    void selectRedis(){
        Article article = (Article) redisUtils.get("1");
        System.out.println(article);
    }

}

切記:使用Java程式向Redis寫入物件時,記得對物件實體類進行序列化

在這裡插入圖片描述

在這裡插入圖片描述