前端的工作挥唠,暫告一段落,這里開始spring boot引入redis之旅
前提:
要安裝好redis,并且可以順利訪問
用IDE創(chuàng)建好一個spring boot項目首先在pom文件中引入
<!-- 整合redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 然后再yml文件中配置redis
spring:
redis:
database: 0
host: 192.168.1.170
port: 6379
password: ******
pool:
max-idle: 8
min-idle: 0
max-active: 8
max-wait: 1
timeout: 3000
- 添加一個簡單的redis工具類,想要更多的方法佛猛,網(wǎng)上找找,有很多坠狡。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
/**
* 功能描述:redis工具類
* 對于redisTpl.opsForValue().set(key, value)進行了一次封裝,不然每次都要這樣保存值
* 而封裝后只需:new RedisClient().set(key,value);
*/
@Component
public class Redis {
@Autowired
private StringRedisTemplate redisTpl; //jdbcTemplate
// 功能描述:設(shè)置key-value到redis中
public boolean set(String key ,String value){
try{
redisTpl.opsForValue().set(key, value);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
// 功能描述:通過key獲取緩存里面的值
public String get(String key){
return redisTpl.opsForValue().get(key);
}
}
- 寫一個測試遂跟,測試redis是否連接成功
import org.junit.Assert;
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.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.DigestUtils;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class RedisTest {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
public void save(){
stringRedisTemplate.opsForValue().set("xudod","supperxudod");
Assert.assertEquals("supperxudod",stringRedisTemplate.opsForValue().get("xudod"));
}
}
- 運行該測試類逃沿,測試通過后可以用redis可視化工具RedisDesktopManager查看剛才添加的鍵值
至此,redis成功引入spring boot幻锁,這篇文章就先寫到這里凯亮。下邊留下一個引子,記錄哄尔,redis在項目中的具體使用
spring boot項目中使用redis--2018年9月5日添加
- 說明假消,前端向后端發(fā)送登錄請求時,會通過lua連接redis做用戶校驗岭接,那么這里設(shè)定富拗,用戶保存和更新時,會同步保存和更新用戶信息到redis鸣戴。這是使用spring boot使用redis的第一個場景
/**
這段代碼是用戶管理實現(xiàn)類中的一個添加用戶的方法
**/
@Override
public BaseResp<Integer> add(UserBase userBase) {
BaseResp<Integer> baseResp = new BaseResp<>();
try {
userBase.setId(UUIDTool.getUUID());
//將用戶信息保存如數(shù)據(jù)庫
int insertSelective = userBaseMapper.insertSelective(userBase);
//將用戶信息寫入redis
boolean redisResult = redis.set(userBase.getAccount(), userBase.getPassword());
if(insertSelective > 0 && redisResult == true) {
baseResp.setCode(BaseResp.SUCCESS);
baseResp.setData(insertSelective);
}else{
baseResp.setCode(BaseResp.ERROR);
baseResp.setData(null);
baseResp.setMessage("無異常啃沪,添加數(shù)據(jù)失敗≌或者用redis緩存數(shù)據(jù)失敶辞А!");
}
} catch (Exception e) {
baseResp.setCode(BaseResp.ERROR);
baseResp.setData(null);
baseResp.setMessage("異常入偷,添加數(shù)據(jù)失斪仿俊:" + e.getMessage());
}
return baseResp;
}