springboot整合Redis 【重點】mysql
使用步驟:
a、添加依賴
pom.xml中:
<!--redis依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
b、在配置文件中配置redis的ip和端口號
spring: #數據源 datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot username: root password: 123456 #SpringBoot jpa jpa: database: mysql show-sql: true generate-ddl: true #redis redis: host: rayfoo.cn port: 6379
c、在代碼中RedisTemplate對象實現操做
//bean對象注入
@Autowired
private RedisTemplate redisTemplate;
@Test public void getRedis(){ //存到redis數據庫 redisTemplate.opsForValue().set("uname","1234"); // 取——上面存入的鍵(key),取時要加上「」 redisTemplate.opsForValue().get("uname")返回值是Object類型 String str = (String)redisTemplate.opsForValue().get("uname"); MUser user = new MUser(); user.setId(1); user.setUsername("小天使"); user.setPassword("123"); user.setName("澤村榮純"); redisTemplate.opsForValue().set("user",user); MUser user1 = (MUser) redisTemplate.opsForValue().get("user"); System.out.println(user1); }