1. 程式人生 > >SpringBoot入門系列:第四篇 redis

SpringBoot入門系列:第四篇 redis

一,準備工作,建立spring-boot-sample-redis工程

1、http://start.spring.io/

     A、Artifact中輸入spring-boot-sample-redis

     B、勾選Web下的web

     C、勾選NOSQL下的Redis

2、Eclips中匯入工程spring-boot-sample-redis

     A、解壓快捷工程spring-boot-sample-redis到某資料夾

     B、eclips中file->import->Import Existing Maven Projects-->Select Maven projects-->finish匯入工程

3、工程匯入之後,檔案結構如下圖

4、在包com.example下建立web資料夾

5、便於測試,引入spring-boot-sample-helloworld的HelloController及配置檔案logback.xml

HelloController程式碼為

package com.example.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

	protected static Logger logger=LoggerFactory.getLogger(HelloController.class);
	
	@RequestMapping("/")
	public String helloworld(){
		logger.debug("訪問hello");
		return "Hello world!";
	}
	
	@RequestMapping("/hello/{name}")
	public String helloName(@PathVariable String name){
		logger.debug("訪問helloName,Name={}",name);
		return "Hello "+name;
	}
}
logback.xml配置為
<configuration>  
    <!-- %m輸出的資訊,%p日誌級別,%t執行緒名,%d日期,%c類的全名,,,, -->  
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">  
        <encoder>  
            <pattern>%d %p (%file:%line\)- %m%n</pattern>
            <charset>GBK</charset> 
        </encoder>  
    </appender>  
    <appender name="baselog"  
        class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <File>log/base.log</File>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <fileNamePattern>log/base.log.%d.i%</fileNamePattern>  
            <timeBasedFileNamingAndTriggeringPolicy  class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">  
        		<!-- or whenever the file size reaches 64 MB -->  
        		<maxFileSize>64 MB</maxFileSize>  
      		</timeBasedFileNamingAndTriggeringPolicy>  
        </rollingPolicy>  
        <encoder>  
            <pattern>  
                %d %p (%file:%line\)- %m%n
            </pattern>  
            <charset>UTF-8</charset> <!-- 此處設定字符集 --> 
        </encoder>  
    </appender>  
    <root level="info">  
        <appender-ref ref="STDOUT" />  
    </root>  
    <logger name="com.example" level="DEBUG">  
        <appender-ref ref="baselog" />  
    </logger>  
</configuration>

注:logback.xml檔案位於src/main/resources下

6、啟動工程,通過瀏覽器檢視正確性

http://localhost:8080/

http://localhost:8080/hello/上帝

二,使用StringRedisTemplate

1、web檔案下建立class,類名為StringRedisController,編寫StringRedisController為

package com.example.web;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StringRedisController {
    
    protected static Logger logger=LoggerFactory.getLogger(StringRedisController.class);
    
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    
    @Resource(name="stringRedisTemplate")
    ValueOperations<String,String> valOpsStr;
    
    @RequestMapping("set")
    public String setKeyAndValue(String key,String value){
        logger.debug("訪問set:key={},value={}",key,value);
        valOpsStr.set(key, value);
        return "Set Ok";
    }
    
    @RequestMapping("get")
    public String getKey(String key){
        logger.debug("訪問get:key={}",key);
        return valOpsStr.get(key);
    }
}
2、修改工程配置檔案application.properties,增加以下內容
#redis資料庫名稱  從0到15,預設為db0
spring.redis.database=1
#redis伺服器名稱
spring.redis.host=127.0.0.1
#redis伺服器密碼
spring.redis.password=123456
#redis伺服器連線埠號
spring.redis.port=6379
#redis連線池設定
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
#spring.redis.sentinel.master=
#spring.redis.sentinel.nodes=
spring.redis.timeout=60000
注:win平臺,下載一個,修改密碼,就可直接執行

3、執行測試

在瀏覽器中先輸入

http://localhost:8080/set?key=lxh2&&value=1001

再輸入

http://localhost:8080/get?key=lxh2

再改改value的值試試

三、使用RedisTemplate

1、在包com.example下建立資料夾domain

2、在domain中建議類person

package com.example.domain;

import java.io.Serializable;

public class Person implements Serializable {

	private static final long serialVersionUID = 1L;

	private String id;
	private String name;
	private Integer age;
	
	
	public Person() {
		super();
	}
	
	
	public Person(String id, String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
}
注意:一定有空的和全欄位的建構函式

3、在domain中建立類PersonDao

package com.example.domain;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

@Repository
public class PersonDao {

	@Autowired
	RedisTemplate<Object,Object> redisTemplate;
	
	@Resource(name="redisTemplate")
	ValueOperations<Object,Object> valOps;
	
	public void save(Person person){
		valOps.set(person.getId(), person);
	}
	
	public Person getPerson(String id){
		return (Person) valOps.get(id);
	}	
}

4、在Web中建立類ObjectRedisController

package com.example.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.domain.Person;
import com.example.domain.PersonDao;

@RestController
public class ObjectRedisController {

	protected static Logger logger=LoggerFactory.getLogger(ObjectRedisController.class);
	
	@Autowired
	PersonDao personDao;
	
	@RequestMapping("/setPerson")
	public void set(String id,String name,Integer age){
		logger.debug("訪問setPerson:id={},name={},age={}",id,name,age);
		Person person=new Person(id,name,age);
		personDao.save(person);
	}
	
	@RequestMapping("/getPerson")
	public Person getPerson(String id){
		return personDao.getPerson(id);
	}
	
}

5、執行測試

http://localhost:8080/setPerson?id=2&&name=lxh2&&age=2

http://localhost:8080/getPerson?id=2